将数组元素解析为固定大小的队列 Python
Parsing array elements to a queue with a fixed size Python
我是编程新手。
我目前拥有的是一个包含 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 效果很好。
看看这个:
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
我认为您不需要排队。为什么不只使用切片:
# 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])
我是编程新手。 我目前拥有的是一个包含 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 效果很好。
看看这个:
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
我认为您不需要排队。为什么不只使用切片:
# 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])