How can I use a for loop to iterate through numbered variables?

二次信任 提交于 2021-01-28 22:37:17

问题


I've got a 20 variables which are named line1, line2, line3.. up to line20. Is there a way in python to use a for loop to reference each of these variables in sequence i.e. iterate through them? Something to this effect:

for i in range(1,21):
    print(line+str(i))

Although I know that's wrong.


回答1:


Don't use separate variables like that. Use a list. Having a bunch of similarly-named variables is an anti-pattern.

lines = []

# add 20 strings to the list

for line in lines:
    print(line)



回答2:


Move your variables in to a list.

So if line1 = "foo" and line2 = "boo" just do this instead:

a = ["foo", "boo"]

for i, v in enumerate(a):
    print("{}: {}".format(i + 1, v))

Will give you an output like:

1: foo
2: boo 

Or if you simply want to just iterate over that array then just do:

for i in a:
    print(i)

Which will simply output:

foo
boo



回答3:


I agree with others that it is better to move to a list, but you could use eval:

>>> line1 = "This"
>>> line2 = "isn't"
>>> line3 = "Recommended"
>>> for i in range(1,4):
    print(eval("line" + str(i)))


This
isn't
Recommended

In addition to the point that it is more natural to use a list, this also isn't recommended because eval can be dangerous. While eval does have some uses and can be used safely (though never safely on a user-input string), avoiding refactoring your code isn't a valid use case. So -- in addition to making your code easier to read and easier to maintain, using lists or dictionaries can also make your code more secure since then you are less likely to use eval in a hackish manner.




回答4:


lst = ['line0', 'line1', 'line2']

for line_num, line_name in enumerate(lst):
    print 'Line str: %s, Line number: %s' % (line_num, line_name)

this will print: Line str: line0, Line number: 0 Line str: line1, Line number: 1 Line str: line02, Line number: 2



来源:https://stackoverflow.com/questions/33153564/how-can-i-use-a-for-loop-to-iterate-through-numbered-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!