如何从python中的列表创建多个项目

时间:2016-01-29 14:44:41

标签: python list

我希望能够从列表中创建单个项目。

例如

test_list = ["dog", "cat", 12, 34, "boop"]

#code code code

item_1 = "dog"
item_2 = "cat"
item_3 = 12
item_4 = 34
item_5 = "boop"

所以我想运行一个遍历列表的循环,并为列表中的每个项创建一个新对象。这可能吗?

2 个答案:

答案 0 :(得分:1)

不要这样做。保持列表不变,因为您已经可以使用test_list[x-1]获取项目编号x或构建字典:

>>> items = {'item_{}'.format(i):thing for i,thing in enumerate(test_list,1)}
>>> items['item_2']
'cat'

由于你的名字不是很有意义(你只是将列表索引偏移一个并在其前添加' item _'),我不认为在这里建立一个字典是特别必要的

答案 1 :(得分:-1)

您可以使用globals()函数返回的字典来设置如下变量:

test_list = ["dog", "cat", 12, 34, "boop"]

for i, x in enumerate(test_list):
    globals()["item_" + str(i + 1)] = x

print item_1
print item_2
print item_3
print item_4
print item_5