Avi*_*tty 1 python python-itertools python-2.7 python-3.x
我有一个 python 列表 [1,2,3,4,5,6]。我想生成长度为 2、3、4 和 5 的所有可能组合。我使用 itertools.combinations 来生成组合,但它不仅仅生成连续组合。例如,长度为 2 的组合应仅为 [1, 2]、[2, 3]、[3, 4]、[4, 5]、[5, 6]。有没有比下面的代码更快的生成方法?
for start, end in combinations(range(len(lst)), 2):
if end - start <= 4 and end-start >= 1:
print(lst[start:end+1])
Run Code Online (Sandbox Code Playgroud)
combinations你根本不需要。你想要的看起来更像是一个滑动窗口。
for i in range(2, 6):
for j in range(len(lst) - i + 1):
print(lst[j:j + i])
Run Code Online (Sandbox Code Playgroud)