Python 中的双端队列附加字典与双端队列(字典)

Deque appending dictionary vs Deque(dictionary) in Python

尝试着把 dictionary 添加到 deque 中。

举个例子:

from collections import deque
graph={}
graph['key']=['value_1','value_2','value_3']
implement_first=deque()
implement_second=deque(graph['key'])
implement_first.append(graph['key'])

如果我打印:

    print(implement_first)
    print(implement_first.popleft())

我明白了 deque([['value_1', 'value_2', 'value_3']]) 并且 ['value_1', 'value_2', 'value_3']

如果我打印:

print(implement_second)
print(implement_second.popleft())

我明白了: deque(['value_1', 'value_2', 'value_3'])value_1

那么这是怎么回事?为什么我要获取 implement_first.append(graph['key']) 的列表列表以及此实现 implement_second=deque(graph['key']) 的作用是什么?

以下2个不等价

d1 = deque(x)

d2 = deque()
d2.append(x)

deque 构造函数采用可迭代对象并附加其所有元素。所以下面的2个是一样的

d1 = deque(x)

d2 = deque()
for y in x:
    d2.append(y)

你的不会引发任何错误,因为 graph["key"] 是一个列表(可迭代的),它可以 变成 a deque一个deque的元素。