【发布时间】: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[:])
-
确实有效。使用切片必须返回我接受的副本?
-
是的,它会复制列表中的每个条目。有些人认为这是复制列表的惯用方式,有些人认为它很丑。