简体   繁体   English

如何在 Python 的条件下应用滑动 window?

[英]How to apply sliding window with conditions in Python?

I have the following list:我有以下列表:

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

I want all the windows of size n= 6 that contains "_-1" and "_1" if the item that contain "_-1" is placed before the item that contain "_1"如果包含"_-1"的项目放在包含“_1”的项目之前,我想要所有大小为n= 6的 windows 包含"_-1""_1" "_1"

It means that I expect the following output这意味着我期望以下 output

[ ('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'), ]

I tried use this function我试过用这个 function

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

and this approach:这种方法:

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

But I don't get any output.但我没有得到任何 output。 What's wrong?怎么了? Any idea?任何想法?

>>> 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')

Edit: *编辑: *

Even shorter:更短:

>>> 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM