python - 如何在 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)))
但我没有得到任何输出。怎么了?任何想法 ?
解决方案
>>> 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)
推荐阅读
- android - 如何在应用程序中添加功能发现?
- java - Primeface 转换器
- vue.js - 如何运行 Vue.js 中使用的 Quasar 项目?
- php - 带有DAYOFWEEK的Mysql嵌套案例
- linux - Docker:Linux Worker 不加入 Windows Master 定义的 Overlay 网络。Windows Worker 工作正常
- amazon-web-services - [AWS Lambda]:如何修复“/lib64/libm.so.6:未找到版本‘GLIBC_2.29’”
- vba - 如何 V 查找工作表 VBA
- ubuntu - Nginx 使用不同的 url 重定向将 POST 请求重定向到 GET 请求
- angular - fixture.detectchanges() 方法导致测试用例失败
- ios - 使用新的 Xcode13+ 编译和运行我的 tvOS 项目,标签栏随 scrollView 滚动,我无法访问拆分视图控制器