假设我有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]
。
这样做最优雅的方式是什么?
答案 0 :(得分: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)]
答案 1 :(得分:2)
另一个选项是切片和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)]
使用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))
或
izip(*[islice(some_lst, s, None) for s in range(3)])
答案 2 :(得分:1)
另一种方式:
subLists = map(lambda x: some_lst[x-1:x+2], some_lst[:-2])