Python: Deque[-1] = Deque.pop() 给出有趣的结果

Python: Deque[-1] = Deque.pop() giving interesting result

我正在使用一个双端队列,想知道为什么下面的代码会这样工作 代码:

import collections

d = collections.deque()
d.append("a")
d.append("b")
d[-1] += d.pop()
print(d)

输出: deque(['bb'])

这让我很吃惊,因为我原以为代码会产生 deque(['ab']) 而不是 deque(['bb'])。为什么会这样?

这一行

d[-1] += d.pop()

等于这条线

d[-1] = d[-1] + d.pop()

python先得到d[-1]也就是'b'

在那之后 运行 d 的 pop 方法和这个方法 return 'b' 在最后 python 为 d[-1]

设置 'bb'

如果你想弹出第一个项目使用popleft()函数。

编辑代码:

from collections import deque


d = deque()

d.append("a")
d.append("b")

d[-1] = d.popleft() + d[-1]

print(d)

输出:

deque(['ab'])

答案很简单:

  • d[-1]+=d.pop() 展开为:d[-1] = d[-1] + d.pop()
  • d[-1] 选择最右边的,这里是 b.
  • d.pop() 在我们的例子中删除了最右边的“b”并附加到 d[-1] 上,它也是上一步中的 b(使这个“bb”)并将其放在d[-1] 是最右边的位置,现在是“a”,因为 d.pop() 用“bb”删除了 b。

前面再加一个就很容易解释了:

import collections
d = collections.deque()
d.append('z')
d.append('a')
d.append('b')
print ("d -1 pos is : "+d[-1])
d[-1]+=d.pop()
print (d)

输出: d -1 位置是:b 双端队列(['z', 'bb'])