如何在Python中创建多个空列表的循环? [英] How to make a loop in Python which creates multiple empty lists?

查看:469
本文介绍了如何在Python中创建多个空列表的循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一行代码来创建一个空列表,该列表的名称由递增变量决定.

I want a line of code which will create an empty list whose name is determined by an incrementing variable.

到目前为止,我到过的所有地方都无济于事.他们建议使用一些可以使列表为空的列表或使用字典的方法.这不是我想要的,我想要一行(或几行)代码仅创建一个空列表(这不是字典或列表列表的一部分,而是一个独立的实体).我希望这些列表是不同的,通过一个变量来区分,该变量每次创建一个新的空列表时都会增加1.

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.

由于我打算在整个递归函数中创建和删除这些列表,因此一开始就不能批量创建这些空列表.我需要制作多个列表,因为我的意图是使此函数下降到新的递归级别,但稍后又返回到上一个列表.它们充当临时工作列表,它们为原始列表的每个项目计算一个值,然后在找到结果后将其复制到最终列表中.

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) = []

如果i = 1,那么我希望这行代码创建一个名为"list_1"的空列表,我可以在整个脚本中继续与之交互.

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.

相反,我遇到了"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...

取决于您的locals用例开关globals,反之亦然.

Depending on your use case switch globals for locals and vice-versa.

一个更好的主意是defaultdict

from collections import defaultdict

my_lists = defaultdict(list)

现在,您不必初始化任何列表,除非您使用它,并且每个键附带的值已经是一个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. 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']})

这篇关于如何在Python中创建多个空列表的循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆