Reputation: 341
I currently have multiple functions as below:
vect_1 = CountVectorizer(parameters)
vect_2 = CountVectorizer(parameters)
vect_3 = CountVectorizer(parameters)
vect_3 = CountVectorizer(parameters)
which I am trying to iterate each one of them. I've tried:
for i in range(4):
vect = vect_[i]
print vect
And I am struggling to correctly defining 'vect' part as it just becomes a string. Any ideas please?
Thanks
Upvotes: 0
Views: 117
Reputation: 236150
This is the pythonic way to do it, using a list:
vects = [
CountVectorizer(parameters),
CountVectorizer(parameters),
CountVectorizer(parameters),
CountVectorizer(parameters)
]
for v in vects:
print(v)
Whenever you see that variable names are being generated dynamically from strings, that's a warning that you need a better data structure to represent your data. Like a list, or a dictionary.
Upvotes: 5
Reputation: 43
I prefer using list or dict
def func_a(a):
print(a)
def func_b(b):
print(b, b)
def func_c(c):
print(c, c, c)
def func_d(d):
print(d, d, d, d)
# use list
func_list = [func_a, func_b, func_c, func_d]
for i in range(4):
func_list[i](i)
# use dict
func_dict = {"vect_1": func_a,
"vect_2": func_b,
"vect_3": func_c,
"vect_4": func_d}
for i in range(1, 5):
func_dict["vect_" + str(i)](i)
which will print
0
1 1
2 2 2
3 3 3 3
1
2 2
3 3 3
4 4 4 4
Upvotes: 0
Reputation: 22
You can just loop through all your parameters.
vectors = []
parameters = []
#Put code for adding parameters here
for parameter in parameters:
vectors.append(CountVectorizer(parameter))
This loops through the parameters you have set and runs the function with each parameter. You can now access all the outputs from the vectors list.
Upvotes: 0
Reputation: 71610
Of course not this, but try globals
(in def use locals
):
for i in range(1,5):
vect = globals()['vect_%s'%i]
print(vect)
Although still the most pythonic way is using @Oscar's solution
Upvotes: 1