从列表中选择相邻的夫妻(或三元组等)

Mic*_*mos 4 python python-2.7 python-3.x

我可以通过使用列表索引来做到这一点......

lst =[1,2,3,4,5,6]
[ [lst[i] , lst[i+1]] for i in range( len(lst) - 1 )]
Run Code Online (Sandbox Code Playgroud)

要么:

lst =[1,2,3,4,5,6]
for i in range(len(lst)-1): 
    entities.append([lst[i],lst[i+1]])
Run Code Online (Sandbox Code Playgroud)

但是有更聪明的方法吗?也许使用迭代器?性能怎么样?

flo*_*ake 5

对于一般解决方案(因为您要求夫妻,三人等),请使用itertools.tee:

from itertools import tee

def adjacent_tuples(iterable, n=2):
    iterators = tee(iterable, n)
    for i, iterator in enumerate(iterators):
        for j in range(i):
            next(iterator)
    return zip(*iterators)
Run Code Online (Sandbox Code Playgroud)

这使用最少的内存,适用于任何长度的元组:

>>> list(adjacent_tuples(range(8), 4))
[(0, 1, 2, 3), (1, 2, 3, 4), (2, 3, 4, 5), (3, 4, 5, 6), (4, 5, 6, 7)]
Run Code Online (Sandbox Code Playgroud)