在Python中使用for循环创建唯一名称列表
我想在一个循环里创建一系列名字独特的列表,并且用循环的索引来生成这些列表的名字。我的想法是这样的:
x = [100,2,300,4,75]
for i in x:
list_i=[]
我想创建一些空的列表,比如:
lst_100 = [], lst_2 =[] lst_300 = []..
有没有人能帮帮我?
3 个回答
0
一种稍微不同的解决方案是使用 defaultdict。这个方法可以让你省去初始化的步骤,因为它会自动使用你选择的类型的默认值。
在这个例子中,我们选择的类型是列表,这样在字典里就会得到空列表:
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d[100]
[]
9
用字典来保存你的列表:
In [8]: x = [100,2,300,4,75]
In [9]: {i:[] for i in x}
Out[9]: {2: [], 4: [], 75: [], 100: [], 300: []}
要访问每个列表:
In [10]: d = {i:[] for i in x}
In [11]: d[75]
Out[11]: []
如果你真的想在每个标签中加上 lst_
:
In [13]: {'lst_{}'.format(i):[] for i in x}
Out[13]: {'lst_100': [], 'lst_2': [], 'lst_300': [], 'lst_4': [], 'lst_75': []}
23
不要创建动态命名的变量。这会让编程变得很麻烦。相反,使用字典(dict)来处理。
x = [100,2,300,4,75]
dct = {}
for i in x:
dct['lst_%s' % i] = []
print(dct)
# {'lst_300': [], 'lst_75': [], 'lst_100': [], 'lst_2': [], 'lst_4': []}