【问题标题】:Locating the first item in a list of lists [duplicate]找到列表列表中的第一项[重复]
【发布时间】:2014-01-31 18:41:12
【问题描述】:

我有这种情况:

>>> y=[[1]]
>>> y=y*2
>>> y
[[1], [1]]
>>> y[0].append(2)
>>> y
[[1, 2], [1, 2]]

我想做的是将 2 添加到外部列表的第一个列表中,即这是所需的输出:

[[1, 2], [1]]

【问题讨论】:

  • 关闭它然后伙计们 - 感谢所有的参考和答案

标签: python list


【解决方案1】:

在做:

y=[[1]]
y=y*2

创建一个包含两个对同一列表对象的引用的列表:

>>> y=[[1]]
>>> y=y*2
>>> id(y[0])  # The id of the first element...
28864920
>>> id(y[1])  # ...is the same as the id of the second.
28864920
>>>

这意味着,当您修改一个时,另一个也会受到影响。


要解决此问题,您可以改用list comprehension

>>> y = [[1] for _ in xrange(2)]  # Use range here if you are on Python 3.x
>>> y
[[1], [1]]
>>> id(y[0])  # The id of the first element...
28864920
>>> id(y[1])  # ...is different from the id of the second.
28865520
>>> y[0].append(2)
>>> y
[[1, 2], [1]]
>>>

【讨论】:

    【解决方案2】:

    y=y*2 替换为 y.append([1]) 以获得不同的引用。

    【讨论】:

    • 不要使用附加。 iCodez 通过使用列表推导具有正确的方法。
    猜你喜欢
    • 2015-01-11
    • 2013-11-17
    • 1970-01-01
    • 2020-03-16
    • 2018-04-19
    • 2022-11-28
    • 1970-01-01
    • 2013-05-09
    相关资源
    最近更新 更多