在Python中查找列表的n长度连续子列表的最优雅方法是什么?

时间:2021-12-28 20:21:40

Let's say I have some_lst = [1, 2, 3, 4, 5, 6, 7, 8, 9] and I want to find all 3 element consecutive sub-lists: [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9].

假设我有some_lst = [1,2,3,4,5,6,7,8,9],我想找到所有3个元素的连续子列表:[1,2,3],[2,3] ,4,[3,4,5],[4,5,6],[5,6,7],[6,7,8],[7,8,9]。

What's the most elegant way of doing this?

这样做最优雅的方式是什么?

3 个解决方案

#1


4  

>>> some_lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l = [some_lst[i:i+3] for i in xrange(len(some_lst)-2)]

#2


2  

Another option is slices and zip:

另一种选择是切片和拉链:

>>> some_lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> zip(some_lst, some_lst[1:], some_lst[2:])
[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9)]

With itertools.islice and itertools.izip you can make it more memory-efficient:

使用itertools.islice和itertools.izip,您可以提高内存效率:

from itertools import islice, izip
izip(islice(some_lst, 0, None),
     islice(some_lst, 1, None),
     islice(some_lst, 2, None))

or

要么

izip(*[islice(some_lst, s, None) for s in range(3)])

#3


1  

yet another way:

另一种方式:

subLists = map(lambda x: some_lst[x-1:x+2], some_lst[:-2])

#1


4  

>>> some_lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l = [some_lst[i:i+3] for i in xrange(len(some_lst)-2)]

#2


2  

Another option is slices and zip:

另一种选择是切片和拉链:

>>> some_lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> zip(some_lst, some_lst[1:], some_lst[2:])
[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9)]

With itertools.islice and itertools.izip you can make it more memory-efficient:

使用itertools.islice和itertools.izip,您可以提高内存效率:

from itertools import islice, izip
izip(islice(some_lst, 0, None),
     islice(some_lst, 1, None),
     islice(some_lst, 2, None))

or

要么

izip(*[islice(some_lst, s, None) for s in range(3)])

#3


1  

yet another way:

另一种方式:

subLists = map(lambda x: some_lst[x-1:x+2], some_lst[:-2])