[英]How do I create a sliding window in Python with different sizes?
I have a list of lists. 我有一份清单清单。 For example:
例如:
a = [[38, 2, 33, 8, 17, 8, 39, 36, 34, 17, 26, 22, 10, 2, 37, 17, 33, 2, 23, 40, 38, 0, 40, 14, 3, 30],
[38, 20, 31, 33, 0, 30, 33, 2, 8, 34, 30, 36, 10, 2, 38, 35, 8, 40, 0, 25, 2, 30, 2, 25]]
This list has about 200 sub-lists (I've provided 2). 这个列表有大约200个子列表(我提供了2个)。 I am looking for a way to output an array containing a sliding window with an arbitrary before and after number of values.
我正在寻找一种方法来输出一个包含滑动窗口的数组,该窗口具有任意数值的前后值。 For example, with two preceding values and three following values, I am trying to get:
例如,有两个前面的值和三个后面的值,我试图得到:
[[_, _, 38, 2, 33, 8],
[_, 38, 2, 33, 8, 17],
[38, 2, 33, 8, 17, 9],
...,
[14, 3, 30, _, _, _,],
[_, _, 38, 20, 31, 33],
...]
I will need to repeat this operation many times (for different sub-lists), and thus speed is important. 我需要多次重复此操作(对于不同的子列表),因此速度很重要。 I am under the impression that converting the data to a Numpy array to use the answer here may be too slow (since each list is of a different length I am guessing I need to instantiate multiple np.arrays).
我的印象是将数据转换为Numpy数组以使用此处的答案可能太慢(因为每个列表的长度不同,我猜我需要实例化多个np.arrays)。 Is there a nice way to do this?
有一个很好的方法来做到这一点? Thank you!
谢谢!
I am fairly sure this is the fastest way of doing it. 我相信这是最快的方法。
def f(b):
ret = []
for sublist in b:
ret.append(["_","_"] + sublist[0:4])
ret.append(["_"] + sublist[0:5])
for i in range(len(sublist)-4):
ret.append(sublist[i:i+5])
ret.append(sublist[-4:] + ["_"])
ret.append(sublist[-3:] + ["_", "_"])
ret.append(sublist[-2:] + ["_", "_", "_"])
return ret
Obviously you have to iterate over every sublist in order to actually achieve the desired result, and for each sublist you have to iterate over it n times in order ot produce n lists, so I'm fairly sure this (o(n^2)) is the fastest you will get it. 显然你必须迭代每个子列表才能真正实现所需的结果,并且对于每个子列表,你必须迭代它n次以生成n个列表,所以我很确定这个(o(n ^ 2) )是你得到它最快的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.