我注意到在我的代码的逻辑顺序试图将值追加到列表时的错误,我的代码工作反正。下面的两个例子说明这个问题。谁能告诉我这是什么回事在第一个例子?
# example 1
text_1 = []
a_1 = []
text_1.append(a_1)
a_1.append('BBB') # this command should be before the last one
print('text 1: ',text_1) # prints [['BBB']]
# example 2
text_2 = []
a_2 = []
text_2.append(a_2)
a_2 = ['BBB'] # this command should be before the last one
print('text 2: ',text_2) # prints [[]]
这里的答案很简单,这两个变量指向内存地址。在第一个例子,你在那个内存地址更改数据。在第二个例子中,你改变了内存地址的变量引用。我评论了你的例子来赚取差价更加清晰:
实施例1:
text_1 = []
a_1 = [] # a_1 refers to a pointer somewhere in memory
# Let's call it LOC_A
# The data at LOC_A is [].
text_1.append(a_1) # appends whatever data is at a_1 as the last element
# a_1 == LOC_A -> []
# text_1 == [LOC_A] == [[]]
a_1.append('BBB') # LOC_A -> ['BBB']
# text_1 == [LOC_A] == [['BBB']]
print('text 1: ',text_1) # prints [['BBB']]
实施例2:
text_2 = []
a_2 = [] # a_2 refers to a pointer somewhere in memory
# let's call this location LOC_A
text_2.append(a_2) # appends whatever data is at LOC_A as the last element
# a_2 == LOC_A -> []
# text_1 == [LOC_A] == [[]]
a_2 = ['BBB'] # a_2 now refers to a different pointer, LOC_B
# a_2 == LOC_B -> ['BBB']
# LOC_A has not changed, is still [], and text_1 still refers to it
# text_1 == [LOC_A] == [[]]
print('text 2: ',text_2) # prints [[]]