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

时间:2020-05-13 08:54:29

标签: python

我想在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]

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

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']]

1 个答案:

答案 0 :(得分:-1)

您可以如下生成列表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']]
相关问题