2

Is there a way to cycle through a group of variables with similar names using a for loop in python?

An example (from the nltk library): I have a group of variables called text1, text2, text3, ..., text9, and I want to do certain operations to all of them without having to explicitly type their names each time, so I'm looking for a way to loop through them like this:

for x in range(1, 9):
    text + x.someFunction()

I know this is not allowed, but is there a way to do something like that?

Arash Saidi
  • 2,228
  • 20
  • 36
  • 1
    You shouldn't be having those variables in the first place. For example, a list called `texts` would be a better solution, then iterating over that is trivial. – Tim Pietzcker Apr 24 '14 at 10:12
  • These variables are in a library (the nltk library) so it isn't me who have named them. – Arash Saidi Apr 24 '14 at 10:14
  • 3
    What a funny library! – devnull Apr 24 '14 at 10:17
  • Assuming it's `nltk.book`, these variables hold example data meant to be used at an interactive prompt while following a tutorial. – user2357112 Apr 24 '14 at 10:21
  • yeah, it's nltk.book. I guess it's not meant to be used the way I am trying to use them, but I don't like following tutorials without doing my own experiments... – Arash Saidi Apr 24 '14 at 10:26

4 Answers4

3

You can use eval:

eval("text" + str(1))

For example, to load your values in a map:

data = dict()
for x in xrange(1, 9):
    key = "text" + str(x)
    data[key] = eval(key)

Or if your variables are objects of a class with a method someFunction:

for x in xrange(1, 9):
    cmd = "text" + str(x) + ".someFunction()"
    eval(cmd)
0

You can use eval

for x in range(1, 9):
    eval('text%d' % x).someFunction()

Refer: What does Python's eval() do? ;

Community
  • 1
  • 1
Buddhima Gamlath
  • 2,318
  • 1
  • 16
  • 26
0

Try this.

for v in (text1, text2, text3):
    v.someFunction()
Kei Minagawa
  • 4,395
  • 3
  • 25
  • 43
0

Make a list:

texts = [text1, text2, text3, text4, text5, text6, text7, text8, text9]

Then you can iterate over it as you would any other list:

for text in texts:

I'm assuming the textn variables aren't expected to change. If you're using the example data from nltk.book, I believe that assumption should hold.

user2357112
  • 260,549
  • 28
  • 431
  • 505