我希望在for循环中创建一系列具有唯一名称的列表,并使用索引来创建列表名称。这是我想要做的:
x = [100,2,300,4,75]
for i in x:
list_i=[]
我想创建空列表,例如
lst_100 = [], lst_2 =[] lst_300 = []..
需要帮助吗?
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': []}
使用字典来保存你的列表:
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': []}
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d[100]
[]
dict
键不是有序的。为了保留插入键的顺序,请使用collections.OrderedDict
:(将dct = {}
改为import collections
,然后跟着dct = collections.OrderedDict()
)。 - unutbu