[英]Call a list variable from a for loop in Python
If I have pre-set list variables that are the same name except for they end in a different number, how can I create variables in a for loop that will call those lists?如果我有相同名称的预设列表变量,但它们以不同的数字结尾,我如何在调用这些列表的 for 循环中创建变量?
My issue is that the variable I create in the for loop is staying as a string.我的问题是我在 for 循环中创建的变量保持为字符串。 I need it to recognize that it's simply a name of a variable.
我需要它来识别它只是一个变量的名称。
Example:示例:
list1 = [2, 4, 3, 7]
list2 = [4, 5, 6]
list3 = [9, 5, 7, 8, 3, 2, 1]
list4 = [4, 1]
for i in range(1,5):
print ("list%d" % (i))
This results in printing the strings:这导致打印字符串:
list1
list2
list3
list4
I want it to print out the actual lists.我希望它打印出实际的列表。
Thanks for any help!感谢您的帮助!
You can achieve below as by using 'eval'.您可以通过使用“eval”来实现以下目标。
list1 = [2, 4, 3, 7]
list2 = [4, 5, 6]
list3 = [9, 5, 7, 8, 3, 2, 1]
list4 = [4, 1]
for i in range(1,5):
print (eval('list%d'% (i)))
But as mentioned in comments, this is not recommended.但正如评论中提到的,不推荐这样做。 You should rewrite by
dict
or list
of list
ie您应该通过
dict
或list
of list
重写,即
my_list = [[2, 4, 3, 7],
[4, 5, 6],
[9, 5, 7, 8, 3, 2, 1],
[4, 1]]
for i in range(len(my_list)):
print (my_list[i])
Note that i change the name of variable list
to my_list
because the word list
is a reserved word.请注意,我将变量
list
的名称更改为my_list
因为单词list
是保留字。
You are printing a string literal (ie plain text) not the actual variable of each list.您正在打印字符串文字(即纯文本)而不是每个列表的实际变量。 One thing you can do is put those lists in a class or a dictionary.
您可以做的一件事是将这些列表放在类或字典中。
Assuming it's a class:假设它是一个类:
class cls:
list1 = [2, 4, 3, 7]
list2 = [4, 5, 6]
list3 = [9, 5, 7, 8, 3, 2, 1]
list4 = [4, 1]
for i in range(1, 5):
print getattr(cls, 'list{}'.format(i))
Assuming it's a dictionary:假设它是一本字典:
lists = {
'list1': [2, 4, 3, 7],
'list2': [4, 5, 6],
'list3': [9, 5, 7, 8, 3, 2, 1],
'list4': [4, 1],
}
for k, v in lists.items():
print '{0}={1}'.format(k, v)
As suggested in the comments you should consider some other data structue to use here.正如评论中所建议的,您应该考虑在此处使用其他一些数据结构。
If you still want this to work.如果你仍然希望这个工作。 You may try as below
您可以尝试如下
for i in range(1,5):
print (eval("list"+str(i)))
the issue with your code that you print a string not the list variable打印字符串而不是列表变量的代码问题
list1 = [2, 4, 3, 7]
list2 = [4, 5, 6]
list3 = [9, 5, 7, 8, 3, 2, 1]
list4 = [4, 1]
for i in list1:
print (i)
new_list=[[2, 4, 3, 7],[4, 5, 6],[9, 5, 7, 8, 3, 2, 1],[4, 1]]
for e in new_list:
print(e)
dic_of_lists={"list1":[2, 4, 3, 7],"list2":[4, 5, 6]
,"list3":[9, 5, 7, 8, 3, 2, 1],"list4":[4, 1]}
#to loop through the dictionary
for key,value in dic_of_lists.items():
print(key+" : ")
print(value)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.