Python 迭代';拉链';numpy数组的范围
我经常使用表示时间序列中关键时刻的numpy数组。然后我想迭代这些范围并对它们运行操作。例如:Python 迭代';拉链';numpy数组的范围,python,arrays,numpy,Python,Arrays,Numpy,我经常使用表示时间序列中关键时刻的numpy数组。然后我想迭代这些范围并对它们运行操作。例如: rngs = [0, 25, 36, 45, ...] output = [] for left, right in zip(rngs[:-1], rngs[1:]): throughput = do_stuff(array[left:right])... output.append(throughput) 有没有一种不那么尴尬的方法呢?您可以使用generator rngs
rngs = [0, 25, 36, 45, ...]
output = []
for left, right in zip(rngs[:-1], rngs[1:]):
throughput = do_stuff(array[left:right])...
output.append(throughput)
有没有一种不那么尴尬的方法呢?您可以使用generator
rngs = [0, 25, 36, 45, ...]
output = []
for index, _ in enumerate(rngs[:-1]):
throughput = do_stuff(array[index:index+1])...
output.append(throughput)
在理解列表的一行中:
rngs = [0, 25, 36, 45, ...]
output = [do_stuff(array[index:index+1]) for index, _ in enumerate(rngs[:-1])]
我认为这与范围内索引(len(rngs)-1)的
没有区别:
,或者Python 2的xrange()
。此外,没有像在索引中那样的元组展开,而且您不必构造rngs[:-1]
。假设rngs
是不规则的,dostuff
一次只能在一个切片上工作,这看起来不错。但也要看一下ufunc.reduceat的可能复制品,尽管我认为他想要一些特别的东西给numpy;不仅仅是一份清单。