比嵌套循环生成所有正切片更好的方法



我想在python中生成列表的所有顺序正片。

有没有比嵌套的 for 循环更整洁的方法?我被困在要搜索的内容上。

因此,对于长度为 3 的列表,我想要以下切片:

input_list[0:1]
input_list[0:2]
input_list[0:3]
input_list[1:2]
input_list[1:3]
input_list[2:3]

这是获取我想要的东西的嵌套 for 循环方式:

input_list = ["stuff", "and", "things"]
output_list = []
for start_index in range(0, len(input_list)):
for end_index in range(1, len(input_list)+1):
if start_index < end_index:
output_list.append(input_list[start_index:end_index])
print(output_list)
# OUTPUT:
>>> [['stuff'], ['stuff', 'and'], ['stuff', 'and', 'things'], ['and'], ['and', 'things'], ['things']]

您可以为列表生成所有索引对,如下所示xs

>>> from itertools import combinations
>>> xs = ["a", "b", "c"]
>>> pairs = combinations(range(len(xs) + 1), 2)
>>> list(pairs)
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]

现在只需为每对切片:

>>> result = [xs[i:j] for i, j in pairs]
>>> result
[['a'], ['a', 'b'], ['a', 'b', 'c'], ['b'], ['b', 'c'], ['c']]

最新更新