使用固定大小的Python将数组元素解析为队列

时间:2017-02-16 12:06:59

标签: python arrays queue fifo

我是编程的新手。 我目前拥有的是一个包含1000多个元素的数组,我想一次只访问其中的10个元素并使用这些元素执行一些操作,然后将数组中的下一个元素输入到队列中,依此类推。 我能想到的一种方法是将数组的所有元素传递到队列中并弹出队列的1个元素,并将其附加到最大大小为10的新队列中。

但我怀疑它是否是正确的方法。 关于我如何处理这个问题的任何线索? 我写的代码到现在为止创建了一个队列并从数组中获取了所有元素。我不确定下一步该做什么。

import numpy as np
class Queue :


    def __init__(self):
        self.items=[]

    def isEmpty(self) :
        return self.items==[]

    def enqueue(self, item):
        self.items.insert(0,item)

    def dequeue(self):
        self.items.pop()

    def size(self):
        return len(self.items)

    def printqueue(self):
        for items in self.items:
            print(items)

q= Queue()
a=np.linspace(0,1,1000)
for i in np.nditer(a):
    q.enqueue(i)

我知道这对专家来说很愚蠢,但我只想知道自己如何处理这个问题。 编辑:这不是blkproc的重复问题。因为我来自C ++背景使用队列是我的想法,但使用切片工作完美。

2 个答案:

答案 0 :(得分:0)

检查出来:

import numpy as np
arr = np.random.randn(1000)
idx = 0
while idx < len(arr):
    sub_arr = arr[idx:idx + 10]
    print(sub_arr)
    idx += 10

答案 1 :(得分:0)

我认为你不需要队列。为什么不使用切片:

# this is the function that is going to act on each group of
# 10 data points
def process_data(data):
    print(data)

slice_len = 10

# here is your data. can be any length.
al = [ii for ii in range(1000)]

for ii in range((len(al) - 1) / slice_len + 1):
    # take a slice from e.g. position 10 to position 20
    process_data(al[(ii * slice_len):(ii + 1) * slice_len])