Python获取子列表
我有一个关于python和列表的非常简单的问题 我需要循环遍历一个列表,得到一个固定长度的子列表,从开始到结束。更清楚地说:Python获取子列表,python,Python,我有一个关于python和列表的非常简单的问题 我需要循环遍历一个列表,得到一个固定长度的子列表,从开始到结束。更清楚地说: def get_sublists( length ): # sublist routine list = [ 1, 2, 3, 4, 5, 6, 7 ] sublist_len = 3 print get_sublists( sublist_len ) 这将返回如下内容: [ 1, 2, 3 ]
def get_sublists( length ):
# sublist routine
list = [ 1, 2, 3, 4, 5, 6, 7 ]
sublist_len = 3
print get_sublists( sublist_len )
这将返回如下内容:
[ 1, 2, 3 ]
[ 2, 3, 4 ]
[ 3, 4, 5 ]
[ 4, 5, 6 ]
[ 5, 6, 7 ]
在python中有什么简单而优雅的方法可以做到这一点吗?使用循环并生成切片:
def get_sublists(length):
for i in range(len(lst) - length + 1)
yield lst[i:i + length]
或者,如果必须返回列表:
def get_sublists(length):
return [lst[i:i + length] for i in range(len(lst) - length + 1)]
灵感来自
说明:三个迭代器是T型的,并被枚举0
,1
,2
。这些列在输出中充当高级i
次的列,有效地将列“向上”移动i
。列压缩为行,最大长度为最短的iterable(最后一列终止于7
)。请考虑:
有关具体的实现,请参见。您有最喜欢的使用收益率语句的指南吗?
lst
不应该是list
?@hellogoodbay:没有,因为使用list
作为变量名从来都不是一个好主意,这会屏蔽内置类型。如何将其应用于列表?我想这个修改需要get_sublist(lst,length)
才能传入一个特定的列表。@pylang:传入一个特定的列表,是的。将lst
作为一个参数而不是闭包或全局参数是非常好的,并且是有效的。也许你看到了下面@Martijn Pieters的答案。最好使用列表
以外的其他变量名,因为列表
是一种内置类型,如果有同名的变量,它将被屏蔽。
[alist[i:i+3] for i in range(len(alist)-2)]
from itertools import izip, tee
def nwise(iterable, n):
z = tee(iterable, n)
for i, x in enumerate(z):
for k in range(i):
next(x)
return izip(*z)
for l in nwise(iter([ 1, 2, 3, 4, 5, 6, 7 ]), 3):
print l
# Output
(1, 2, 3)
(2, 3, 4)
(3, 4, 5)
(4, 5, 6)
(5, 6, 7)
import more_itertools as mit
lst = [ 1, 2, 3, 4, 5, 6, 7 ]
list(mit.windowed(lst, 3))
# [(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7)]