【问题标题】:How can I create the following arrays如何创建以下数组
【发布时间】:2010-12-09 13:46:21
【问题描述】:

如何为列表中的项目创建数组 像

list = ["a","b","c"]
  for thing in list:
    thing = [] 

【问题讨论】:

  • 结果应该是什么?目前,您似乎想用一个空列表替换 list 中的每个项目(您应该给它另一个名称):[[], [], []]
  • id 最终喜欢,a = [], b = [], c = []
  • @user428370:编写简单的赋值语句似乎比玩循环更简单。让这件事变得更复杂有什么意义?

标签: python arrays


【解决方案1】:

我认为对您所要求的严格回答是:

for x in lst: 
    locals()[x] = []

locals 可能是 globals,这取决于您想要什么。但通常建议使用字典来保存这些值(正如其他人已经提出的那样)。

[编辑]另一种方式:

locals().update(dict.fromkeys(lst, []))

【讨论】:

  • 上面这个例子正是我所需要的,谢谢
【解决方案2】:

如果您的意思是创建全局数组(模块级别),那么您可以这样做:

for thing in list:
    globals()[thing] = []

【讨论】:

    【解决方案3】:
    x = dict ([(name, []) for name in ["a", "b", "c"]])
    

    ?

    或许

    x = [[] for name in ["a", "b", "c"]]
    

    【讨论】:

      【解决方案4】:

      [list() for i in items]

      [list() for i in range(len(items))]

      如果你想将items的当前元素包装在列表中,你可以这样做

      [[i] for i in items]

      items 用于变量名,因为list 是内置的。

      【讨论】:

        【解决方案5】:
        list = ["a","b","c"]
        for thing in list:
          exec(thing+"=[]")
        

        这是你想要的吗?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-02-27
          • 1970-01-01
          • 2013-12-14
          • 2021-12-17
          • 2013-12-09
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多