【问题标题】:creating and naming multiple lists with a for-loop [duplicate]使用for循环创建和命名多个列表[重复]
【发布时间】:2022-01-12 00:28:43
【问题描述】:

我有一个包含几个元素的列表:

list = ["a", "b", "c", "d", "e", "f", "g"]

我需要一个 for 循环,它会生成多个列表,其中包含除一个元素之外的所有元素,并且还想适当地命名它们。它应该看起来像这样:


for i in list:
    globals()['list_' + str(i)] = list.remove(i)

结果应该是这样的:

list_a = ["b", "c", "d", "e", "f", "g"]
list_b = ["a", "c", "d", "e", "f", "g"]
list_c = ["a", "b", "d", "e", "f", "g"] 
list_d = ["a", "b", "c", "e", "f", "g"]
ect...

【问题讨论】:

  • 做。不是。做。这。使用字典。
  • 不要这样做。使用一个容器,比如另一个list,或者在此处使用dict。不要动态修改变量。
  • 注意,list.remove(i) 返回None,你为什么期待别的东西?你必须建立一个新的列表。注意,你不应该在迭代列表时修改它

标签: python list for-loop


【解决方案1】:

您可以使用字典:

lst = ["a", "b", "c", "d", "e", "f", "g"]
dic = {}
for item in lst:
    dic['list_' + item] = [x for x in lst if not x == item]
print(dic)

输出:

{'list_a': ['b', 'c', 'd', 'e', 'f', 'g'], 'list_b': ['a', 'c', 'd', 'e', 'f', 'g'], 'list_c': ['a', 'b', 'd', 'e', 'f', 'g'], 'list_d': ['a', 'b', 'c', 'e', 'f', 'g'], 'list_e': ['a', 'b', 'c', 'd', 'f', 'g'], 'list_f': ['a', 'b', 'c', 'd', 'e', 'g'], 'list_g': ['a', 'b', 'c', 'd', 'e', 'f']}

【讨论】:

  • 不要使用名称dict - 它会覆盖内置的。
猜你喜欢
  • 2018-06-04
  • 2020-11-14
  • 2015-03-31
  • 2021-12-01
  • 1970-01-01
  • 2014-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多