【问题标题】:dynamically declare/create lists in python [closed]在python中动态声明/创建列表[关闭]
【发布时间】:2013-08-08 12:44:30
【问题描述】:

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

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

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

谢谢你的期待

【问题讨论】:

    标签: python list dynamic creation variable-declaration


    【解决方案1】:

    您可以使用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
    [[], [], [], []]
    

    【讨论】:

    • 谢谢..但是我在使用第一种方法时遇到错误 g['depth_{}'.format(i)] = [] ValueError: zero length field name in format
    • @ChithraNair,我更新了代码以在 Python 2.6 上运行。
    • 在尝试打印 depths_1 时,它告诉我们未定义的变量!是的,我想我可以使用列表列表
    • @ChithraNair,我使用depth_.. 而不是depths_.. 作为变量名。
    • 红标?您可能正在使用 IDE。许多 IDE 不处理以这种方式创建的变量。正如其他人回答的那样,以这种方式(使用全局变量)制作变量并不是一个好方法。
    【解决方案2】:

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

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

    或者使用globalslocals 之类的技巧。但不要那样做。这不是一个好的选择:

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

    【讨论】:

    • 谢谢。但是我在执行这个 g['depth_{}'.format(i)] = [] ValueError: zero length field name in format 时遇到以下错误
    • 请问,为什么使用 globals() 不是一个好的选择?
    • 它将在全局命名空间中注册变量。有时会导致混乱。
    【解决方案3】:

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

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

    现在您可以改用depth[1] 来调用depth_1。如果可能的话,你应该从depth[0]开始。

    那么您的代码将改为depth = []

    【讨论】:

    • 真的很有帮助。非常感谢你
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多