查找序列中长度为n的所有连续子序列 [英] Find all consecutive sub-sequences of length n in a sequence

查看:374
本文介绍了查找序列中长度为n的所有连续子序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到序列中长度为n的所有连续子序列.

I want to find all consecutive sub-sequences of length n in a sequence.

例如说n为3,顺序为:

E.g. say n was 3 and the sequence was:

[0,1,7,3,4,5,10]

我想要一个可以作为输出产生的函数:

I want a function that would produce as output:

[[0,1,7],[1,7,3],[7,3,4],[3,4,5],[4,5,10]]

提前谢谢!

推荐答案

>>> x = [0,1,7,3,4,5,10]
>>> n = 3
>>> zip(*(x[i:] for i in range(n)))
[(0, 1, 7), (1, 7, 3), (7, 3, 4), (3, 4, 5), (4, 5, 10)]

如果您希望结果是列表列表而不是元组列表,请使用map(list, zip(...)).

If you want the result to be a list of lists instead of list of tuples, use map(list, zip(...)).

这篇关于查找序列中长度为n的所有连续子序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆