从Python列表中获取元素的所有唯一组合

问题描述 投票:0回答:1

我查找了许多相关问题,但没有人真正回答我如何接收列表中所有元素的组合。例如,使用此输入列表

input_list = ["apple", "orange", "carrot"]

我想要这个清单:

output_list = [ ["apple"], ["orange"], ["carrot"], ["apple", "orange"],  ["apple", "carrot"], ["orange", "carrot"], ["apple", "orange", "carrot"]]

即我也想包含单个条目,我该怎么做?

python list combinations itertools
1个回答
0
投票

这几乎是您想要的,减去一些格式:

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')]]
© www.soinside.com 2019 - 2024. All rights reserved.