简体   繁体   中英

Function that returns all sub-sequences in a list that are successive

I have this function

def conseq_sequences(li, length):
    """ Takes a list and a length. Returns all sub-sequences in li that
    are successice (e.g. [1,2,3] or [5,6,7,8]) and of the right length.

    E.g.  >>> conseq_sequences([1,6,7,8,9,8,9], length=3)
          [[6,7,8], [7,8,9]]
    """
    return [li[n:n + length] for n in range(len(li) - length + 1)
            if li[n:n + length] == range(li[n], li[n] + length)]

This function is present in a class, and I can not understand way it does not work. When I invoke it, I get an empty sequence.

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

Can someone help to make the modification in it in order to return all sub-sequences in list that are successive, as in the example?

In Python 3.x, range doesn't return a list, but a range object.

>>> range(1, 10)
range(1, 10)
>>> type(range(1, 10))
<class 'range'>
>>> [1, 2, 3] == range(1, 4)
False
>>> [1, 2, 3] == list(range(1, 4))
True

So, you need to explicitly convert that to a list, and then compare, like this

[li[n:n + length] for n in range(len(li) - length + 1)
    if li[n:n + length] == list(range(li[n], li[n] + length))]

Here, we create a new list, by converting the range object to a list, with

list(range(li[n], li[n] + length))

Demo

Python 3.4.0 (default, Apr 11 2014, 13:05:11) 
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def conseq_sequences(li, length):
...     """ Takes a list and a length. Returns all sub-sequences in li that
...     are successice (e.g. [1,2,3] or [5,6,7,8]) and of the right length.
... 
...     E.g.  >>> conseq_sequences([1,6,7,8,9,8,9], length=3)
...           [[6,7,8], [7,8,9]]
...     """
...     return [li[n:n + length] for n in range(len(li) - length + 1)
...             if li[n:n + length] == list(range(li[n], li[n] + length))]
... 
>>> conseq_sequences([1, 6, 7, 8, 9, 8, 9], 3)
[[6, 7, 8], [7, 8, 9]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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