我有一个列表中包含项目的列表,我想为每个列表命名,我不知道列表中的项目数量是多少:
lists = [[1.0, 2.0], [3.0, 4.0, 1.0, 2.0]...]
#result:
0 = [1.0, 2.0]
1 = [3.0, 4.0, 1.0, 2.0]
... = []
#I have this script but doesn’t work
number_of_items = len(listas)
names = range(number_of_items)
for x in names:
for i in listas:
x = [i]
#any advice?
答案 0 :(得分:1)
你可以将它们全部放在字典中,例如:
lists = [[1.0, 2.0], [3.0, 4.0, 1.0, 2.0], [4,5,6]]
out_dict = {}
for i,l in enumerate(lists):
out_dict[i] = l
print(out_dict)
# which gives
{0: [1.0, 2.0], 1: [3.0, 4.0, 1.0, 2.0], 2: [4, 5, 6]}
但是如果你使用0,1,2作为键/名称,它就像使用原始列表一样。
或者,您可以按如下方式将变量添加到命名空间:
for i,l in enumerate(lists):
locals()['v'+str(i)] = l
print(v0, v1, v2)
#[1.0, 2.0] [3.0, 4.0, 1.0, 2.0] [4, 5, 6]
答案 1 :(得分:0)
lists = [[1.0, 2.0], [3.0, 4.0, 1.0, 2.0]]
for x,i in zip(range(len(lists)),lists):
print str(x) + " = " + str(i)
此处使用的zip()
函数用于同时迭代您之前使用的两个循环。这样可以打印预期结果。
答案 2 :(得分:0)
使用字典
>>> lm = {}
>>> l1 = [1,2,3]
>>> l2 = [4,5,6]
>>> l3 = [7,8,9]
>>> lm["l1"] = l1
>>> lm["l2"] = l2
>>> lm["l3"] = l3
>>> lm
{'l2': [4, 5, 6], 'l3': [7, 8, 9], 'l1': [1, 2, 3]}
>>> lm["l1"]
[1, 2, 3]