我很難試圖瞭解下面的代碼的行爲。在Python 3.6中List.append/extend +運營商和+ =
下面的示例代碼是我的實際代碼的抽象。我已經這樣做了,以更好地描述我的問題。我正在嘗試將列表添加到另一個列表。產生二維列表。爲了檢查會員資格,以後再查看該清單。雖然我不能設法以我想要的方式添加我的列表。
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 [:]) – happydave
確實有效。使用切片必須返回我採取的副本? –
是的,它複製列表中的每個條目。有些人認爲這是複製清單的慣用方式,有些人認爲這很醜陋。 – happydave