在列表中附加值的逻辑顺序(Python)

时间:2019-02-05 18:19:46

标签: python list append

在尝试将值附加到列表中时,我发现代码的逻辑顺序错误,但我的代码仍然有效。下面的两个示例说明了该问题。有人可以告诉我第一个示例中的情况吗?

# 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 个答案:

答案 0 :(得分:0)

这里的简单答案是变量指向内存地址。在第一个示例中,您更改该内存地址上的数据。在第二个示例中,您更改变量所引用的内存地址。我已评论您的示例,以使区别更加明显:

示例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 [[]]