首页 > 解决方案 > 如何在 Python 中应用带有条件的滑动窗口?

问题描述

我有以下列表:

l = ["test1_-1", "test2_-1", "test3_-1","test4_-1", "test5_0", "test6_0", 
         "test7_1", "test8_1", "test9_1", "test10_-1", "test11_-1" ]

我想要包含的所有大小的窗口,如果包含的项目n= 6放在包含的项目之前 "_-1""_1""_-1""_1"

这意味着我期望以下输出

[ ('test2_-1', 'test3_-1', 'test4_-1', 'test5_0', 'test6_0', 'test7_1'), ('test3_-1', 'test4_-1', 'test5_0', 'test6_0', 'test7_1', 'test8_1'), ('test4_-1', 'test5_0', 'test6_0', 'test7_1', 'test8_1', 'test9_1'), ]

我尝试使用此功能

from itertools import islice
def window(seq, n=6):
    it= iter(seq)
    result = tuple(islice(it, n))
    if len(result) == n:
        yield result
    for elem in it:
        result = result[1:] + (elem,)
        yield result

这种方法:

for item in(list(window(l,6))):
    if  "_-1"  in item and "_1" in item:
        print(list(window(l,6)))

但我没有得到任何输出。怎么了?任何想法 ?

标签: python

解决方案


>>> for item in window(l,6):
...   if any([elem.endswith("_-1") for elem in item]):
...     underscore_dash_indexes = [idx for idx, elem in enumerate(item) if elem.endswith("_-1")]
...     if any([elem.endswith("_1") for elem in item]):
...       underscore_indexes = [idx for idx, elem in enumerate(item) if elem.endswith("_1")]
...       if max(underscore_dash_indexes) < min(underscore_indexes):
...         print(item)
('test2_-1', 'test3_-1', 'test4_-1', 'test5_0', 'test6_0', 'test7_1')
('test3_-1', 'test4_-1', 'test5_0', 'test6_0', 'test7_1', 'test8_1')
('test4_-1', 'test5_0', 'test6_0', 'test7_1', 'test8_1', 'test9_1')

编辑: *

更短:

>>> for item in window(l,6):
...   underscore_dash_indexes = [idx for idx, elem in enumerate(item) if elem.endswith("_-1")]
...   underscore_indexes = [idx for idx, elem in enumerate(item) if elem.endswith("_1")]
...   if underscore_dash_indexes and  underscore_indexes  and max(underscore_dash_indexes) < min(underscore_indexes):
...     print(item)

推荐阅读