【发布时间】:2017-02-08 01:41:26
【问题描述】:
如果 dimension 变大,我的这部分代码将无法扩展。
我遍历我的数据并在每个 dt 时间窗口累积它们。为此,我比较了上下时间值。当我达到上限时,我打破 for 循环 以提高效率。下次我运行 for 循环 时,我不想从它的开头开始,而是从我之前停止的元素开始,以提高效率。 我该怎么做?
我试图删除/弹出列表的元素,但索引搞砸了。我读到我无法修改循环遍历的列表,但我的目标似乎并不少见,所以必须有解决方案。我不关心代码后面的原始数据列表,我只想优化我的积累。
# Here I generate data for you to show my problem
from random import randint
import numpy as np
dimension = 200
times = [randint(0, 1000) for p in range(0, dimension)]
times.sort()
values = [randint(0, dimension) for p in range(0, dimension)]
data = [(values[k], times[k]) for k in range(dimension)]
dt = 50.0
t = min(times)
pixels = []
timestamps = []
# this is my problem
while (t <= max(times)):
accumulator = np.zeros(dimension)
for idx, content in enumerate(data):
# comparing lower bound of the 'time' window
if content[1] >= t:
# comparing upper bound of the 'time' window
if (content[1] < t + dt):
accumulator[content[0]] += 1
# if I pop the first element from the list after accumulating, indexes are screwed when looping further
# data.pop(0)
else:
# all further entries are bigger because they are sorted
break
pixels.append(accumulator)
timestamps.append(t)
t += dt
【问题讨论】:
标签: python list numpy iteration