在python中动态声明/创建列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18098326/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:54:45  来源:igfitidea点击:

dynamically declare/create lists in python

pythonlistdynamiccreationvariable-declaration

提问by Cheese

I am a beginner in python and met with a requirement to declare/create some lists dynamically for in python script. I need something like to create 4 list objects like depth_1,depth_2,depth_3,depth_4 on giving an input of 4.Like

我是 python 的初学者,遇到了在 python 脚本中动态声明/创建一些列表的要求。我需要像创建 4 个列表对象,例如 depth_1,depth_2,depth_3,depth_4 来输入 4.Like

for (i = 1; i <= depth; i++)
{
    ArrayList depth_i = new ArrayList();  //or as depth_i=[] in python
}

so that it should dynamically create lists.Can you please provide me a solution to this?

以便它应该动态创建列表。你能为我提供一个解决方案吗?

Thanking You in anticipation

感谢你在期待

采纳答案by falsetru

You can do what you want using globals()or locals().

您可以使用globals()或做您想做的事情locals()

>>> g = globals()
>>> for i in range(1, 5):
...     g['depth_{0}'.format(i)] = []
... 
>>> depth_1
[]
>>> depth_2
[]
>>> depth_3
[]
>>> depth_4
[]
>>> depth_5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'depth_5' is not defined

Why don't you use list of list?

为什么不使用列表列表?

>>> depths = [[] for i in range(4)]
>>> depths
[[], [], [], []]

回答by zhangyangyu

You can not achieve this in Python. The way recommended is to use a list to store the four list you want:

您无法在 Python 中实现这一点。推荐的方式是使用一个列表来存储你想要的四个列表:

>>> depth = [[]]*4
>>> depth
[[], [], [], []]

Or use tricks like globalsand locals. But don't do that. This is not a good choice:

或者使用像globals和这样的技巧locals。但不要那样做。这不是一个好的选择:

>>> for i in range(4):
...     globals()['depth_{}'.format(i)] = []
>>> depth_1
[]

回答by zhangyangyu

I feel that depth_iis risky and so wouldn't use it. I'd recommend that you use the following approach instead:

我觉得这depth_i有风险,所以不会使用它。我建议您改用以下方法:

depth = [[]]

for i in range(4):
    depth.append([])

Now you can just call depth_1by using depth[1]instead. If possible, you should start from depth[0].

现在你可以depth_1通过 usingdepth[1]来调用。如果可能,您应该从depth[0].

Then your code will be depth = []instead.

那么你的代码将是depth = []