我正在尝试在 python 中使用 deque 创建一个队列。
我不断收到的错误是索引超出范围
perf_his[b][c] = 0
IndexError: 双端队列索引超出范围
这是我实现的代码的一个小原型(prototype)。
import collections
apps = [1,2,3]
num_thrs = len(apps)
perf_his = []
for a in range(num_thrs):
perf_his += [collections.deque(maxlen=1)]
for b in range(num_thrs):
for c in range(0, 1):
perf_his[b][c] = 0
为了检查我是否正确理解双端队列,我实现了这段代码:
#!/usr/bin/env python
from collections import deque
something = ["foo","bar","baz"]
output = []
diff = 0
d = deque()
for i in something:
d.append(i)
print("-> %s" % i)
for i in xrange(len(d)):
print(d[i])
output.append(d[i])
for i in xrange(len(something)):
if output[i] != something[i]:
diff += 1
print(something,output,diff)
我一直在尝试在大约 2 天内修复错误,但我似乎不明白这个问题。 有人可以解释一下吗?
最佳答案
在您的第一段代码中,您永远不会append()
deque
,因此它永远不会有元素“0” ,因此不允许您分配给它。设置 maxlen
不会创建元素,它只会限制以后可以出现的元素数量。
您可能想要的是:
for a in range(num_thrs):
perf_his += [collections.deque()]
for b in range(num_thrs):
for c in range(0, 1):
perf_his[b].append(0)
关于python - collections-deque 中的错误 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14550090/