【问题标题】:Parsing array elements to a queue with a fixed size Python将数组元素解析为具有固定大小 Python 的队列
【发布时间】:2017-07-05 12:53:57
【问题描述】:

我是编程新手。 我目前拥有的是一个包含 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++ 背景,所以我想到了使用队列,但使用 slice 效果很好。

【问题讨论】:

标签: python arrays queue fifo


【解决方案1】:

我认为您不需要排队。为什么不只使用切片:

# 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])

【讨论】:

  • 这正是我想要做的,谢谢:)
【解决方案2】:

看看这个:

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

【讨论】:

    猜你喜欢
    • 2018-12-18
    • 2013-02-16
    • 1970-01-01
    • 1970-01-01
    • 2018-05-17
    • 1970-01-01
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多