Python:查找特定长度的所有连续子序列

时间:2014-05-25 23:28:21

标签: python algorithm list

我有一个整数列表,我想在这个列表中找到长度为n的所有连续子序列。例如:

>>> int_list = [1,4,6,7,8,9]
>>> conseq_sequences(int_list, length=3)
[[6,7,8], [7,8,9]]

我能想到的最好的是:

def conseq_sequences(self, li, length):
    return [li[n:n+length]
            for n in xrange(len(li)-length+1)
            if li[n:n+length] == range(li[n], li[n]+length)]

这不是过于可读。有没有可读的pythonic方式这样做?

4 个答案:

答案 0 :(得分:2)

这是一个更通用的解决方案,适用于任意输入迭代(不仅仅是序列):

from itertools import groupby, islice, tee
from operator import itemgetter

def consecutive_subseq(iterable, length):
    for _, consec_run in groupby(enumerate(iterable), lambda x: x[0] - x[1]):
        k_wise = tee(map(itemgetter(1), consec_run), length)
        for n, it in enumerate(k_wise):
            next(islice(it, n, n), None) # consume n items from it
        yield from zip(*k_wise)

示例:

print(*consecutive_subseq([1,4,6,7,8,9], 3))
# -> (6, 7, 8) (7, 8, 9)

该代码使用Python 3语法,如果需要,可以适用于Python 2.

另见What is the most pythonic way to sort dates sequences?

答案 1 :(得分:1)

一种解决方案如下:

import numpy # used diff function from numpy, but if not present, than some lambda or other helper function could be used. 

def conseq_sequences(li, length):
    return [int_list[i:i+length] for i in range(0, len(int_list)) if sum(numpy.diff(int_list[i:i+length]))==length-1]

基本上,首先,我从列表中获得给定长度的连续子列表,然后检查其元素的差异总和是否等于length - 1

请注意,如果元素是连续的,则它们的差异将累加到length - 1,例如对于子列表[5,6,7],其元素的差异为[1, 1],其总和为2

但说实话,不确定这个解决方案是否比你的解决方案更清晰或更加pythonic。

如果您没有numpydiff函数可以轻松定义如下:

def diff(l):
  '''For example, when l=[1,2,3] than return is [1,1]'''  
  return [x - l[i - 1] for i, x in enumerate(l)][1:]

答案 2 :(得分:0)

使用operator.itemgetteritertools.groupby

 def conseq_sequences(li, length):
    res = zip(*(li[i:] for i in xrange(length)))
    final = []
    for x in res:
        for k, g in groupby(enumerate(x), lambda (i, x): i - x):
            get_map = map(itemgetter(1), g)
            if len(get_map) == length:
                final.append(get_map)
    return final

没有进口。

def conseq_sequences(li, length):
    res = zip(*(li[i:] for i in xrange(length)))
    final = []
    for ele in res:
        if all(x == y+1 for x, y in zip(ele[1:], ele)):
            final.append(ele)
    return final

可以将其转化为列表理解:

def conseq_sequences(li, length):
    res = zip(*(li[i:] for i in xrange(length)))
    return [ ele for ele in res if all(x == y+1 for x, y in zip(ele[1:], ele))]

答案 3 :(得分:0)

 def condition (tup):
    if tup[0] + 1 == tup[1] and tup[1] + 1 == tup[2] :
        return True
    return False

 def conseq_sequence(li):
   return [x for x in map(None, iter(li), iter(li[1:]), iter(li[2:])) if condition(x)]