【问题标题】:How to increment the name of a list in python如何在python中增加列表的名称
【发布时间】:2012-01-06 19:55:07
【问题描述】:

我希望能够增加列表的名称,以便创建多个空列表。

例如,我想要。

List_1 = [] 
List_2 = []
...
List_x = []

我一直在工作:

for j in range(5):            #set up loop
  list_ = list_ + str(j)     # increment the string list so it reads list_1, list_2, ect
  list_ = list()             # here I want to be able to have multiple empty lists with unique names
  print list_

【问题讨论】:

    标签: python list naming


    【解决方案1】:

    这样做的正确方法是创建一个列表。

    list_of_lists = []
    for j in range(5):
       list_of_lists.append( [] )
       print list_of_lists[j]
    

    然后,您可以通过以下方式访问它们:

    list_of_lists[2] # third empty list
    list_of_lists[0] # first empty list
    

    如果你真的想要这样做,虽然你可能不应该这样做,你可以使用exec

    for j in range(5):
        list_name = 'list_' + str(j)
        exec(list_name + ' = []')
        exec('print ' + list_name)
    

    这会在list_name 下的字符串中创建名称,然后使用exec 执行该动态代码。

    【讨论】:

    • 我回答了同样的问题,但把这个例子搞砸了,很糟糕:) 所以你得到了 +1。
    • +1,但强调“这样做的正确方法是拥有一个列表列表”,并且不要使用exec/locals
    【解决方案2】:

    我强烈推荐organgeoctopus的回答,但为了如何在Python中做到这一点:

    # BAD HACK
    for i in range(5):
        locals()['list_%d' % i] = []
    

    【讨论】:

    • 比我建议的 exec 更好。虽然不好的做法,但我喜欢 python 让你做这样的事情。它让我走了不少弯路!
    • locals() 永远不应该被修改。 docs.python.org/library/functions.html#locals
    • 我不知道修改locals() 有多危险,谢谢。我已经编辑了我的帖子,但为了显示locals() 的可用性,我会保留它,因为它对于阅读非常有用。
    • 使用没有类似警告的globals()。它将在模块级别创建东西。
    • 修改 locals() 并不危险,它有时不起作用(由于 CPython 如何优化函数内部的局部变量访问)。有一些方法可以强制它工作(只需在函数中的任何位置包含一个exec,即使在它不会被执行的地方),但这些都是依赖于实现的,而且变量访问速度也很慢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多