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

2024-10-02 16:21:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我想能够从一个列表中创建单个项目。你知道吗

例如

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"

因此,我想运行一些循环,遍历列表,并为列表中的每个项创建一个新对象。这可能吗?你知道吗


Tags: 项目对象test列表codeitemlistcat
2条回答

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

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

因为你的名字不是很有意义(你只是将列表索引偏移1,然后在它前面加上'item\),我不认为在这里建立字典是特别必要的。你知道吗

可以使用^{}函数返回的字典设置如下变量:

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

相关问题 更多 >