2017-02-16 38 views
0

我是编程的新手。 我目前拥有的是1000+个元素的数组,我只想一次只访问这些元素中的10个,然后使用这些元素执行一些操作,然后将数组中的下一个元素输入到队列中,等等。 我能想到的一种方法是将数组中的所有元素传入队列并弹出队列中的1个元素,并将其添加到最大大小为10的新队列中。将数组元素解析为具有固定大小的队列Python

但我怀疑它的正确方法它。 任何导致我如何处理这个问题? 我直到现在编写的代码创建了一个队列,并从数组中获取所有元素。我不确定接下来我该做什么。

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++背景使用队列在我的脑海中,但使用切片完美工作。

+0

的可能重复[我怎样才能有效地处理块类似于Matlab的blkproc(blockproc)功能的numpy的阵列(http://stackoverflow.com/questions/5073767/how -can-i-efficient-process-a-numpy-array-in-blocks-similar-to-matlabs-blkpro) – Torxed

+0

或者也许这样:http://stackoverflow.com/questions/19712919/combining-numpy-arrays- in-blockwise-form – Torxed

回答

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]) 
+0

这正是我想要做的,谢谢:) – srikarpv

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