【问题标题】:List.append/extend + operators and +=List.append/extend + 运算符和 +=
【发布时间】:2017-11-23 19:01:20
【问题描述】:

我很难理解下面这段代码的行为。在 python 3.6 中

下面的示例代码是我实际代码的抽象。我这样做是为了更好地描述我的问题。我正在尝试将一个列表添加到另一个列表中。产生一个二维列表。出于检查成员资格的目的,稍后再查看该列表。虽然我无法以我想要的方式添加我的列表。

a_list = []
another_list = [7,2,1]

a_list.DONT_KNOW(another_list)
another_list = [7,3,1]

结果:

a_list
[[7,2,1]]
another_list
[7,3,1]

我的问题示例:

class foo:
    def __init__(self):
        self.a_list = []
        self.another_list = [0]
####### Modifying .extend/.append##############
        self.a_list.append(self.another_list) #  .append() | .extend(). | extend([])
###############################################
    def bar(self):
######## Modifying operator########
        self.another_list[0] += 1 #              += | +
###################################
        print('a_list = {} another_list = {} '.format(self.a_list, self.another_list))

def call_bar(f, repeats):
    x = repeats
    while x > 0:
        x -= 1
        foo.bar(f)

f = foo()
call_bar(f,3)

重复 5 次。修改 list.function 和增量运算符。输出

        # .append() and +=
a_list = [[1]] another_list = [1]
a_list = [[2]] another_list = [2]
a_list = [[3]] another_list = [3]

        # .extend() and +=
a_list = [0] another_list = [1]
a_list = [0] another_list = [2]
a_list = [0] another_list = [3]

        # .append() and +
a_list = [[1]] another_list = [1]
a_list = [[2]] another_list = [2]
a_list = [[3]] another_list = [3]

        #.extend() and +
a_list = [0] another_list = [1]
a_list = [0] another_list = [2]
a_list = [0] another_list = [3]

        #.extend([]) and +
a_list = [[1]] another_list = [1]
a_list = [[2]] another_list = [2]
a_list = [[3]] another_list = [3]

请注意,在所有这些示例中,当我获得二维数组(我需要)时。 a_list 中的值在操作 another_list 时会发生变化。我如何获得执行此操作的代码?

     #SOME METHOD I DON'T KNOW
a_list = [[0]] another_list = [1]
a_list = [[0]] another_list = [2]
a_list = [[0]] another_list = [3]

【问题讨论】:

  • a_list.append(another_list[:])
  • 确实有效。使用切片必须返回我接受的副本?
  • 是的,它会复制列表中的每个条目。有些人认为这是复制列表的惯用方式,有些人认为它很丑。

标签: python list append extend


【解决方案1】:

您必须使用self.a_list.append(self.another_list.copy()) 创建another_list 的快照,然后将其添加到a_list。您的代码实际上将another_list 添加为a_list 的元素,因此以后的编辑会更改该对象的内容是很自然的。

【讨论】:

  • 太棒了!谢了哥们。有道理,虽然不是很明显。\
【解决方案2】:

如果您希望a_list 保持为[[0]] 而不管another)list 中的第一个值发生了什么,为什么不在__init__ 中将其初始化为[[0]]

def __init__(self):
    self.a_list = [[0]]
    self.another_list = [0]
    # End of __init__; nothing else

使用append,您可以添加another_list 的引用作为a_list 的第一个元素。使用extend,您可以将another_list 的元素的引用添加到a_list

【讨论】:

  • 不是我想要达到的目标。尽管对附加和扩展的解释表示赞赏:)
  • Np,但你想达到什么目的? B/c 我的答案产生的结果与您标记为正确的结果相同,但它避免调用copy()
  • “我正在尝试将一个列表添加到另一个列表。结果是一个二维列表。为了稍后检查该列表的成员资格。”
猜你喜欢
  • 2016-07-31
  • 2012-11-26
  • 2020-01-25
  • 2016-02-19
  • 1970-01-01
  • 2013-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多