在python中生成列表的所有组合

在python中生成列表的所有组合

本文介绍了在python中生成列表的所有组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是问题:

给出Python中的项目列表,我将如何获得这些项目的所有可能组合?

Given a list of items in Python, how would I go by to get all the possible combinations of the items?

此网站上有几个类似的问题,建议使用itertools.combine,但仅返回我需要的一部分:

There are several similar questions on this site, that suggest using itertools.combine, but that returns only a subset of what I need:

stuff = [1, 2, 3]
for L in range(0, len(stuff)+1):
    for subset in itertools.combinations(stuff, L):
        print(subset)

()
(1,)
(2,)
(3,)
(1, 2)
(1, 3)
(2, 3)
(1, 2, 3)

如您所见,它仅按严格顺序返回项目,而不返回(2,1),(3,2),(3,1),(2、1、3),(3、1、2 ),(2、3、1)和(3、2、1).有一些解决方法吗?我似乎什么都没想.

As you see, it returns only items in a strict order, not returning (2, 1), (3, 2), (3, 1), (2, 1, 3), (3, 1, 2), (2, 3, 1), and (3, 2, 1). Is there some workaround that? I can't seem to come up with anything.

推荐答案

使用 itertools.permutations:

>>> import itertools
>>> stuff = [1, 2, 3]
>>> for L in range(0, len(stuff)+1):
        for subset in itertools.permutations(stuff, L):
                print(subset)
...
()
(1,)
(2,)
(3,)
(1, 2)
(1, 3)
(2, 1)
(2, 3)
(3, 1)
....

关于itertools.permutations的帮助:

permutations(iterable[, r]) --> permutations object

Return successive r-length permutations of elements in the iterable.

permutations(range(3), 2) --> (0,1), (0,2), (1,0), (1,2), (2,0), (2,1)
>>>

这篇关于在python中生成列表的所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 16:55