简体   繁体   English

如何在Python中进行循环以创建多个空列表?

[英]How to make a loop in Python which creates multiple empty lists?

I want a line of code which will create an empty list whose name is determined by an incrementing variable. 我想要一行代码,它将创建一个空列表,其名称由递增变量确定。

Everywhere I've looked thus far has been unhelpful. 到目前为止,我到过的所有地方都无济于事。 They suggest instead something which makes a list of empty lists or using a dictionary. 他们建议使用一些可以使列表为空列表或使用字典的方法。 This is not what I want, I want a line (or several) of code which just creates an empty list (which is not part of a dictionary or a list of lists, a stand alone entity). 这不是我想要的,我想要一行(或几行)代码创建一个空列表(这不是字典或列表列表的一部分,它是一个独立的实体)。 I want these lists to be distinct, distinguished by a variable which increments by 1 every time a new empty list is created. 我希望这些列表是不同的,每个变量由创建一个新的空列表时增加1的变量来区分。

These empty lists can't be made in one batch at the very beginning as I intend to make and delete these lists throughout a recursive function. 由于我打算在整个递归函数中创建和删除这些列表,因此一开始就不能批量创建这些空列表。 I need to make multiple lists as my intention is for this function to descend to a new level of recursion but return later to the previous list. 我需要制作多个列表,因为我的意图是使此函数下降到新的递归级别,但稍后再返回到上一个列表。 These are acting as temporary working lists which calculate a value for each item of an original list and then copy the result into a final list once it is found. 这些充当临时工作列表,它们为原始列表的每个项目计算一个值,然后在找到结果后将其复制到最终列表中。

str("list_" + i) = []

If i = 1, then I would like this line of code to create an empty list with the name "list_1" which I can proceed to interact with throughout my script. 如果i = 1,那么我希望这一行代码创建一个名称为“ list_1”的空列表,我可以继续在整个脚本中进行交互。

Instead I'm met with "SyntaxError: can't assign to function call" 相反,我遇到了"SyntaxError: can't assign to function call"

By all means let me know if I'm not making any sense at all and I will do my best to convey my request. 一定要让我知道我是否毫无意义,我会尽力传达我的要求。

Highly advise against this but this achieves what you want depending on your use case: 强烈建议您这样做,但这会根据您的用例实现您想要的:

globals()['list_' + str(i)] = []

for i in range(5):
    globals()['list_' + str(i)] = []

list_1
[]

list_2
[]

etc...

Depending on your use case switch globals for locals and vice-versa. 根据您的用例,请为locals切换globals ,反之亦然。

A better idea would be defaultdict 一个更好的主意是defaultdict

from collections import defaultdict

my_lists = defaultdict(list)

Now you don't have to initialize any list until you use it and every key comes with it's value being a list already. 现在,您不必初始化任何列表,直到您使用它并且每个键都附带它的值已经是list For example: 例如:

for i in range(5):
    my_lists['list_' + str(i)].append('foo')

my_lists

defaultdict(list,
            {'list_0': ['foo'],
             'list_1': ['foo'],
             'list_2': ['foo'],
             'list_3': ['foo'],
             'list_4': ['foo']})

This is bad practice but anyway: 这是不好的做法,但无论如何:

for i in range(10):       # for global vars
    globals()["list_" + str(i)] = []
print(list_0) # []

Maybe what you're looking for is a dictionary: 也许您正在寻找的是字典:

items = dict()
for i in range(10):       # for dictionary 
    items[str("list_" + i)] = []
print(items.list_0) # []

Avoid globals , use defaultdict 避免使用globals ,请使用defaultdict

Using a collections.defaultdict is both efficient and manageable. 使用collections.defaultdict既高效易于管理。 You don't need to add keys explicitly when appending to list values: 追加到列表值时,无需显式添加键:

from collections import defaultdict
dd = defaultdict(list)
dd['list_0'].append('foo')

print(dd)
# defaultdict(<class 'list'>, {'list_0': ['foo']})

If you want to explicitly add keys, even with empty list values, you can do so by feeding an extra argument: 如果您想显式添加键,即使具有空列表值,也可以通过提供一个额外的参数来做到:

from collections import defaultdict
dd = defaultdict(list, **{k: [] for k in [f'list_{i}' for i in range(5)]})

print(dd)
# defaultdict(<class 'list'>, {'list_0': [], 'list_1': [], 'list_2': [],
#                              'list_3': [], 'list_4': []})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM