在python中动态声明/创建列表 [英] dynamically declare/create lists in python
本文介绍了在python中动态声明/创建列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
for (i = 1; i< = depth; i ++)
{
ArrayList depth_i = new ArrayList(); //或作为depth_i = []在python
}
,以便它应该动态创建列表。可以请你提供一个解决方案吗?
感谢你的预期
解决方案
您可以使用 globals()
或 localals()
。 >
>>> g = globals()
>>>>对于我的范围(1,5):
... g ['depth_ {0}'。format(i)] = []
...
>> ; depth_1
[]
>>> depth_2
[]
>>> depth_3
[]
>>> depth_4
[]
>>>> depth_5
追溯(最近的最后一次呼叫):
文件< stdin>,第1行,< module>
NameError:name'depth_5'未定义
为什么不使用列表列表?
>>>深度= [[] for i in range(4)]
>>>>深度
[[],[],[],[]]
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
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
解决方案
You can do what you want using globals()
or 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
[[], [], [], []]
这篇关于在python中动态声明/创建列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文