簡體   English   中英

我如何創建以下數組

[英]How can I create the following arrays

我如何為列表中的項目創建數組,例如

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

我認為對您提出的要求的嚴格回應是:

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

locals可能是globals ,這取決於你想要什么。 但是通常建議改用字典來保存這些值(就像其他人已經提出的那樣)。

[編輯]另一種方式:

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

如果要創建全局數組(模塊級別),則可以執行以下操作:

for thing in list:
    globals()[thing] = []
x = dict ([(name, []) for name in ["a", "b", "c"]])

或者可能

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

[list() for i in items]

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

如果您想將items的當前元素包裝在列表中,可以執行

[[i] for i in items]

items是變量名,因為list是內置的。

list = ["a","b","c"]
for thing in list:
  exec(thing+"=[]")

這是你想要的嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM