这个程序为什么会输出[5,5,5,[1,3,'Hello','Barney']]
而不是5,5,5
?给出了意外的结果集?
aList=[1,3,"Hello","Barney"]
bList=[5,5,5]
aList.append(bList)
if(5 in aList):
print(aList)
else:
aList.pop().append(aList)
print(bList)
这个程序为什么会输出[5,5,5,[1,3,'Hello','Barney']]
而不是5,5,5
?给出了意外的结果集?
aList=[1,3,"Hello","Barney"]
bList=[5,5,5]
aList.append(bList)
if(5 in aList):
print(aList)
else:
aList.pop().append(aList)
print(bList)
您附加bList
到aList
,然后再弹出它关闭,附加aList
至bList
。
这里是通过步骤发生步骤:
aList.append(bList)
添加bList
作为一个单一的值来aList
; aList
现在是:
>>> aList=[1,3,"Hello","Barney"]
>>> bList=[5,5,5]
>>> aList.append(bList)
>>> aList
[1, 3, 'Hello', 'Barney', [5, 5, 5]]
注意嵌套列表; list.append()
将参数作为目标列表中的单个条目添加。
然后测试5
是否在aList
;它不是,它是在一个嵌套列表:
>>> 5 in aList
False
>>> 5 in aList[-1]
True
的else
分支使用list.pop()
以除去最后一个元素,这是一个整体嵌套列表,并追加aList
它; bList
仍然是指最后的名单:
>>> temp = aList.pop()
>>> temp
[5, 5, 5]
>>> temp is bList
True
>>> temp.append(aList)
>>> bList
[5, 5, 5, [1, 3, 'Hello', 'Barney']]
你可能想延长aList
代替,加入刚刚元素bList
到aList
:
>>> aList=[1,3,"Hello","Barney"]
>>> bList=[5,5,5]
>>> aList.extend(bList)
>>> aList
[1, 3, 'Hello', 'Barney', 5, 5, 5]
现在5 in aList
是True
,并且bList
不会受到影响。
我很少看到这么好解释的答案:-) – Grimmy
因为,aList.pop()
实际上返回bList
,并且您将aList
的内容附加到它。
你的代码以一种稍微复杂的方式执行'bList.append(aList)'。 – Matthias