繁体   English   中英

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

[英]Get all unique combinations of elements from list in Python

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

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

我想要这个清单:

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

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

您正在寻找powerset itertools 配方

from itertools import chain, combinations

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

>>> input_list = ["apple", "orange", "carrot"]
>>> print(list(map(list, powerset(input_list)))[1:])
[['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')]]

oneliner 的答案是:

[list(j) for i in range(len(input_list )) for j in itertools.combinations(input_list , i+1)]

第一个循环 ( i ) 遍历所有不同的组合并创建组合对象,然后第二个循环 ( j ) 遍历组合的每个元素并创建一个列表,然后将其附加到原始列表中。 输出如您所愿,无需更改任何内容。

itertools文档为使用模块轻松实现的事情提供了一组有用的方法; 其中有一个 powerset 生成器:

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

给定您的字符串列表,您将获得一个tuples列表。

>>> list(powerset(input_list))
[(), ('apple',), ('orange',), ('carrot',), ('apple', 'orange'), ('apple', 'carrot'), ('orange', 'carrot'), ('apple', 'orange', 'carrot')]

空元组很容易过滤,必要时可以将元组转换为列表。

>>> list(list(x) for x in powerset(input_list) if x != ())
[['apple'], ['orange'], ['carrot'], ['apple', 'orange'], ['apple', 'carrot'], ['orange', 'carrot'], ['apple', 'orange', 'carrot']]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM