如何从另一个列表中的字符串创建列表。python

2024-03-29 10:18:28 发布

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

我在想,有没有一种方法可以将列表中的字符串转换为python中的列表?例如,我有一个列表:teams = ['team_one', team_two', team_three,]。如何从中获得三个单独的空列表? team_one = []team_two = []team_three = [] 谢谢大家!


3条回答

您可以使用for循环添加到字典(或者创建具有列表理解的字典,如@Blotosmetek所评论的)。两者都做同样的事情

d = {}

for item in teams:
    d[item] = []

编辑:

事后看来,for循环可以用来创建变量,而不需要字典

for item in teams:
    item = []

您正在谈论动态创建变量。理想情况下,您不应该这样做,而应该使用典型的数据结构

如果有必要,你可以做这样的事

    for name in teams:
        globals()[name] = 0

    for i in range(10):
        globals()['variable{}'.format(i)] = 0

有关为什么这是个坏主意的更多信息,请查看this链接

下面是一个稍微容易理解的代码,但仍然是一个坏主意

>>> name = input("Enter a variable name: ")
Enter a variable name: X
>>> globals()[name] = 42
>>> X
42

在一般情况下,这不是一个好主意,但如果被迫这样做,您可以:

>>> teams = ['team_one', 'team_two', 'team_three']
>>> for i in teams:
...     exec(i + ' = []')
... 
>>> team_one
[]
>>> team_two
[]
>>> team_three
[]

相关问题 更多 >