【问题标题】:Find consecutive combinations [duplicate]查找连续组合[重复]
【发布时间】:2012-06-11 04:12:10
【问题描述】:

可能重复:
Rolling or sliding window iterator in 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 或其他一些预先构建的模块中是否有可以做这种事情的东西?

【问题讨论】:

  • 对我来说看起来不错。我不认为组合是正确的词。您正在做的是返回给定序列的给定长度的所有 子序列
  • Ruby 称之为Enumerable#each_slice
  • @JoelCornett:实际上,这些是子字符串,而不是子序列;子序列不一定是连续的。请注意,与大多数编程语言相比,字符串在理论计算机科学中具有更广泛的含义。
  • @larsmans:好点。对于 OP 的参考,维基百科条目:en.wikipedia.org/wiki/Substring#Substring
  • 子字符串!呃,不知道我想不出的心理障碍在哪里。这正是我的意思。

标签: python combinations


【解决方案1】:

我喜欢务实的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))))

太多is...

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

【讨论】:

    【解决方案2】:

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

    def subsequences(iterable, length):
        return [iterable[i: i + length] for i in xrange(len(iterable) - length + 1)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-25
      • 2017-07-03
      • 2017-06-02
      • 2016-02-16
      • 2016-08-24
      • 2019-11-23
      • 2022-01-20
      • 1970-01-01
      相关资源
      最近更新 更多