0

I am a newbie to programming . What i currently have is an array with 1000+ elements , i want to access only 10 of these elements at a time and perform some operations with these elements then input the next element in the array into the queue and so on. One method i could think of is pass all the elements of the array into the queue and pop 1 element of queue and append it into the new queue with max size 10.

But i doubt if its the right way to do it. Any leads as to how i must approach this problem? The code i have written until now creates a queue and takes in all the elements from the array. I am not sure of what i must do next.

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)

I know this is silly for the experts but just wanted to know how i can approach this on my own. Edit : It was not a duplicate question of blkproc. as i come from C++ background using a queue was on my mind but using slice worked perfectly.

srikarpv
  • 33
  • 7
  • Possible duplicate of [How can I efficiently process a numpy array in blocks similar to Matlab's blkproc (blockproc) function](http://stackoverflow.com/questions/5073767/how-can-i-efficiently-process-a-numpy-array-in-blocks-similar-to-matlabs-blkpro) – Torxed Feb 16 '17 at 12:19
  • Or maybe this: http://stackoverflow.com/questions/19712919/combining-numpy-arrays-in-blockwise-form – Torxed Feb 16 '17 at 12:20

2 Answers2

0

Check this out:

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
peidaqi
  • 673
  • 1
  • 7
  • 18
0

I don't think you need a queue. Why not just use a slice:

# 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])
daphtdazz
  • 7,754
  • 34
  • 54