python - collections-deque 中的错误 - Python

标签 python deque

我正在尝试在 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/

相关文章:

python - Featuretools:即使没有日期时间相关列,它是否可以应用于单个表以生成特征?

python - 我怎样才能在 python 中发出声音?

python - Hadoop Mapreduce:如何将数据从映射器分区到reducer

c++ - 如何在 std::deque 中避免 `deque iterator not dereferencable`?锁?

c++ - 空双端队列与未使用的指向双端队列的指针

python - 解析 SQL 查询文本以提取使用的表名称

Python 3.6 请求 SSLerror "unexpected eof while reading'

java - 为什么我无法从 PriorityQueue 中删除通过 peek() 获取的元素?

python - 如何在双端队列中打印项目(python)

Python - deq 函数打印 8 次 - 防止只打印一次?