0

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

3
  • 7
    Don't try to do this. Use a list. Commented Sep 17, 2018 at 9:49
  • 2
    why don't you put them in a list/tuple? vect = [CountVectorizer(parameters), ...] Commented Sep 17, 2018 at 9:49
  • You don't have "multiple functions", you have multiple variables. Commented Sep 17, 2018 at 10:10

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Didn't downvote, but you shouldn't do this. Use a list from the start.
0

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.

Comments

0

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

1 Comment

A dictionary with integer keys? A list would be a better fit anyway. I'd agree to use a dictionary if the keys are 'vect_1', 'vect_2', etc., to mirror the variables in the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.