【问题标题】:Append one item to multiple lists Python将一项附加到多个列表 Python
【发布时间】:2020-10-28 16:58:45
【问题描述】:
item_1 = foo

list_1 = []
list_2 = []
list_3 = []

是否可以将item_1 附加到list_1list_2list_3 在一行中?

list_1.append(item_1)
list_2.append(item_1)
list_3.append(item_1)

对我来说似乎很糟糕;我有将近 20 个列表,我需要所有列表中的一项。

【问题讨论】:

  • 您可以将所有列表放入另一个列表中,然后对其进行迭代并添加您的项目。
  • 当你有类似x_1, x_2, ...这样类型和用途的变量时,你应该考虑将它们放在一个列表或其他允许批量处理的集合中。
  • 拥有 20 个列表,全部独立管理,包含相同的项目,无论哪种方式都感觉很糟糕。你能想到更好的设计吗?
  • y = lambda x: (list_1.append(x), list_2.append(x), list_2.append(x)) y(item_1)
  • 也许有更好的设计方法,@DeepSpace,但我是新手,目前我没有看到更好的方法......

标签: python list append


【解决方案1】:

使用循环:

lists_to_append_to = [list1,list2]
for list in lists_to_append_to:
     list.append(item_1)

如果列表的名称确实是 list_1,2 等,您可能应该使用字典:

lists = {
    1: list(),
    2: list()
}

在这种情况下,在循环中使用字典。

for current_list in lists:
     lists[current_list].append(item)

【讨论】:

  • dict 循环在迭代键时有点偏离。此外,list 是一个糟糕的变量名,因为它隐藏了内置类型。
  • @Johnfishmaster 谢谢你的提示,但我的项目目前已经够复杂了,就像我之前说的,我是新手,对字典不太熟悉。
  • 这是使用它们的额外理由。尝试新事物是学习的一部分。但是,您应该只在用于类似目的时才使用它。
【解决方案2】:

我们可以创建一个列表列表并使用 for 循环遍历所有列表。

item_1 = 'foo'

list_1 = []
list_2 = []
list_3 = []

这里我们创建一个列表列表(可以是任意长度):

mylist = [list_1, list_2, list_3]

接下来,我们逐个遍历主列表中的所有列表。 每个列表都将被目标变量(在本例中为“l”)引用,然后我们可以在 l 上调用.append()

for l in mylist:
    l.append(item_1)

为了证明这是可行的,我们可以检查主列表和单个列表:

print(mylist)
[['foo'], ['foo'], ['foo']]

print(list_1)
['foo']

print(list_2)
['foo']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 2023-01-07
    • 2015-07-11
    • 2020-10-29
    相关资源
    最近更新 更多