繁体   English   中英

Pythonic:查找一定长度的所有连续子序列

[英]Pythonic: Find all consecutive sub-sequences of certain length

我有一个整数列表,我想在此列表中找到长度为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方式可以做到这一点吗?

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

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。

另请参见, 对日期序列进行排序的最pythonic方法是什么?

一种解决方案如下:

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。

万一您没有numpy ,可以轻松定义diff函数,如下所示:

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:]

使用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))]
 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)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM