我是Python的初学者,在编写Python脚本时遇到了需要动态声明/创建一些列表的要求。我需要像这样创建4个列表对象,例如depth_1、depth_2、depth_3、depth_4,当输入为4时。
for (i = 1; i <= depth; i++)
{
ArrayList depth_i = new ArrayList(); //or as depth_i=[] in python
}
我希望它可以动态创建列表。您能否提供解决方案?
非常感谢。
我是Python的初学者,在编写Python脚本时遇到了需要动态声明/创建一些列表的要求。我需要像这样创建4个列表对象,例如depth_1、depth_2、depth_3、depth_4,当输入为4时。
for (i = 1; i <= depth; i++)
{
ArrayList depth_i = new ArrayList(); //or as depth_i=[] in python
}
我希望它可以动态创建列表。您能否提供解决方案?
非常感谢。
你可以使用 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
为什么不使用列表的列表?
>>> depths = [[] for i in range(4)]
>>> depths
[[], [], [], []]
>>> depth = [[]]*4
>>> depth
[[], [], [], []]
或者使用像globals
和locals
这样的技巧。但不要那样做。这并不是一个好选择:
>>> for i in range(4):
... globals()['depth_{}'.format(i)] = []
>>> depth_1
[]
我认为使用depth_i
是有风险的,因此我不会使用它。我建议你使用以下方法代替:
depth = [[]]
for i in range(4):
depth.append([])
depth[1]
来调用depth_1
。如果可能的话,你应该从depth[0]
开始。depth = []
。