在 python 的 for 循环中创建唯一名称列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14819849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
create lists of unique names in a for -loop in python
提问by brain storm
I want to create a series of lists with unique names inside a for-loop and use the index to create the liste names. Here is what I want to do
我想在 for 循环中创建一系列具有唯一名称的列表,并使用索引创建列表名称。这是我想要做的
x = [100,2,300,4,75]
for i in x:
list_i=[]
I want to create empty lists such as
我想创建空列表,例如
lst_100 = [], lst_2 =[] lst_300 = []..
any help?
有什么帮助吗?
采纳答案by unutbu
Don't make dynamically named variables. It makes it hard to program with them. Instead, use a 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': []}
回答by root
Use a dictionary to hold your lists:
使用字典来保存您的列表:
In [8]: x = [100,2,300,4,75]
In [9]: {i:[] for i in x}
Out[9]: {2: [], 4: [], 75: [], 100: [], 300: []}
To access each list:
要访问每个列表:
In [10]: d = {i:[] for i in x}
In [11]: d[75]
Out[11]: []
And if you really want to have lst_in each label:
如果你真的想lst_在每个标签中都有:
In [13]: {'lst_{}'.format(i):[] for i in x}
Out[13]: {'lst_100': [], 'lst_2': [], 'lst_300': [], 'lst_4': [], 'lst_75': []}
回答by JCash
A slight variation to the other's dict-solutions is to use a defaultdict. It allows you to skip the initialisation step by invoking the chosen type's default value.
其他人的 dict-solutions 的一个细微变化是使用 defaultdict。它允许您通过调用所选类型的默认值来跳过初始化步骤。
In this case the chosen type is a list, which will give you empty lists in the dictionary:
在这种情况下,选择的类型是一个列表,它会给你字典中的空列表:
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d[100]
[]

