5

可能重复:
Python 中的滚动或滑动窗口迭代器

我是编程新手,正在学习 Python。我正在寻找一种有效/pythonic 的方法来解决问题。

我想要一个返回包含父可迭代组合的可迭代列表的函数,只要组合中的元素与原始父可迭代出现相同的连续顺序即可。

如果将这个概念描述为“连续”的正确词通常意味着“重复相同的元素”,我不确定“连续”是否正确。例如 [1,1,1]、'aaa' 等...

我的意思是给定列表 [1,2,3,4,5]:

[1,2,3] 是连续的,但 [1,2,4] 不是。(有这个词吗?)

这是consecutive_combinations()我创建的函数和预期的行为:

def consecutive_combinations(iterable, consec):
    begin = 0
    chunks = len(iterable) + 1 - consec
    return [iterable[x + begin: x + consec] for x in xrange(chunks)]

def test():
    t = (1,2,3,4,5)
    s = "The quick brown fox jumps over the lazy dog."
    CC = consecutive_combinations
    assert CC(t, 2) == [(1, 2), (2, 3), (3, 4), (4, 5)]
    assert CC(t, 3) == [(1, 2, 3), (2, 3, 4), (3, 4, 5)]
    assert CC(t, 4) == [(1, 2, 3, 4), (2, 3, 4, 5)]
    assert CC(t, 5) == [(1, 2, 3, 4, 5)]
    assert CC(s, 3) == ['The', 'he ', 'e q', ' qu', 'qui', 'uic', 'ick', 'ck ', 'k b', ' br', 'bro', 'row', 'own', 'wn ', 'n f', ' fo', 'fox', 'ox ', 'x j', '  ju', 'jum', 'ump', 'mps', 'ps ', 's o', ' ov', 'ove', 'ver', 'er ', 'r t', '    th', 'the', 'he ', 'e l', ' la', 'laz', 'azy', 'zy ', 'y d', ' do', 'dog', 'og. ']
    assert CC('', 3) == []
    print "All tests passed!"

test()

这是一个有效的解决方案吗?itertools 或其他一些预先构建的模块中是否有可以做这种事情的东西?

4

2 回答 2

7

我喜欢务实的zip方法:

n = 3
s = "The quick brown fox jumps over the lazy dog."
zip(*(s[i:] for i in xrange(n)))

它不是超高效的,它只适用于序列,但它通常足以完成这项工作。

相应的itertools解决方案是对上述内容的非常简单的转换:

from itertools import izip, islice, tee

def slices(iterable, n):
    return izip(*(islice(it, i, None) for i, it in enumerate(tee(iterable, n))))

这么多i...

尽管如此,这应该适用于任何可迭代的(但对于像列表或字符串这样的普通序列可能会更慢)。

于 2012-06-10T19:40:28.973 回答
3

你的解决方案很好。但是,您可以将其缩短一点。例如:

def subsequences(iterable, length):
    return [iterable[i: i + length] for i in xrange(len(iterable) - length + 1)]
于 2012-06-10T19:43:48.293 回答