在Python中获取列表的所有组合

时间:2020-06-27 13:23:16

标签: python combinations itertools

我想获取列表的所有组合:

L = ["a","b","c"]
combinations(L,length=2)
# [("a","a"),("a","b"),("a","c"),("b","a"),("b","b"),("b","c"),("c","a"),("c","b"),("c","c")]

我尝试过

itertools.combinations()

但这又返回了

[('a', 'b'), ('a', 'c'), ('b', 'c')]

当我使用itertools.permutations()时,它只是返回具有迭代长度的组合,这也不是我想要的。

我可以使用任何库/函数而无需编写自己的库/函数吗?

5 个答案:

答案 0 :(得分:3)

您可以将itertools.productrepeat=2一起使用,如下所示:

from itertools import product

L = ["a","b","c"]
print(list(product(L, repeat=2)))
#[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]

答案 1 :(得分:2)

简单的列表组合也可以完成这项工作。

L = ["a","b","c"]
print([(a,b) for a in L for b in L])
#[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]

答案 2 :(得分:1)

itertools模块具有一个名为product的功能,您正在寻找它。

>>> L = ["a", "b", "c"]
>>> list(itertools.product(L, repeat=2))
[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]

答案 3 :(得分:1)

itertools的产品功能提供了解决方案。

In [17]: from itertools import product

In [18]: L = ["a","b","c"]

In [19]: list(product(L, L))
Out[19]:
[('a', 'a'),
 ('a', 'b'),
 ('a', 'c'),
 ('b', 'a'),
 ('b', 'b'),
 ('b', 'c'),
 ('c', 'a'),
 ('c', 'b'),
 ('c', 'c')]

答案 4 :(得分:-1)

您可以使用itertools.permutations()的第二个参数:

Functor

输出:

scala> :kind -v List
List's kind is F[+A]
* -(+)-> *
This is a type constructor: a 1st-order-kinded type.

scala> :kind -v cats.Functor
cats.Functor's kind is X[F[A]]
(* -> *) -> *
This is a type constructor that takes type constructor(s): a higher-kinded type.

scala> :kind -v cats.Functor[List]
cats.Functor[List]'s kind is A
*
This is a proper type.

从文档中:

from itertools import permutations

L = ["a","b","c"]

print([n for n in permutations(L,2)]+[(i,i) for i in L])

返回可迭代元素的连续r长度排列。 如果未指定r或为None,则r默认为可迭代的长度,并生成所有可能的全长置换。