我查找了许多相关问题,但没有人真正回答我如何接收列表中所有元素的组合。例如,使用此输入列表
input_list = ["apple", "orange", "carrot"]
我想要这个清单:
output_list = [ ["apple"], ["orange"], ["carrot"], ["apple", "orange"], ["apple", "carrot"], ["orange", "carrot"], ["apple", "orange", "carrot"]]
即我也想包含单个条目,我该怎么做?
这几乎是您想要的,减去一些格式:
from itertools import combinations
input_list = ["apple", "orange", "carrot"]
combis = [[i for i in combinations(input_list, 1)], [i for i in combinations(input_list, 2)], [i for i in combinations(input_list, 3)]]
输出:
[[('apple',), ('orange',), ('carrot',)],
[('apple', 'orange'), ('apple', 'carrot'), ('orange', 'carrot')],
[('apple', 'orange', 'carrot')]]