Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中的for循环中创建唯一名称的列表_Python_List_For Loop_Unique - Fatal编程技术网

在python中的for循环中创建唯一名称的列表

在python中的for循环中创建唯一名称的列表,python,list,for-loop,unique,Python,List,For Loop,Unique,我想在for循环中创建一系列具有唯一名称的列表,并使用索引创建列表名称。这是我想做的 x = [100,2,300,4,75] for i in x: list_i=[] 我想创建空列表,例如 lst_100 = [], lst_2 =[] lst_300 = [].. 有什么帮助吗?不要创建动态命名的变量。这使得与他们一起编程变得很困难。相反,使用dict: x = [100,2,300,4,75] dct = {} for i in x: dct['lst_%s' % i

我想在for循环中创建一系列具有唯一名称的列表,并使用索引创建列表名称。这是我想做的

x = [100,2,300,4,75]

for i in x:

  list_i=[]
我想创建空列表,例如

lst_100 = [], lst_2 =[] lst_300 = []..

有什么帮助吗?

不要创建动态命名的变量。这使得与他们一起编程变得很困难。相反,使用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': []}

使用字典保存您的列表:

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\uu

In [13]: {'lst_{}'.format(i):[] for i in x}
Out[13]: {'lst_100': [], 'lst_2': [], 'lst_300': [], 'lst_4': [], 'lst_75': []}

另一个dict解决方案的一个微小变化是使用defaultdict。它允许您通过调用所选类型的默认值跳过初始化步骤

在这种情况下,所选类型是一个列表,它将为您提供字典中的空列表:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d[100]
[]

这是我的第一个想法,你先去做:P@F3AR3DLEGEND--我认为这是最具python风格的方式:)这是字典理解吗?:-)在保持原始x的顺序的同时,有没有办法处理?相反,我在这里看到,在root的回答中,“100,2300,4,75”顺序没有得到保留。我想这是一个dict属性。@Coolio2654:对
dict
键未订购。要保留插入键的顺序,请使用:(更改
dct={}
-->
import collections
,后跟
dct=collections.orderedict()
)。