我不相信以前曾问过这个确切的问题。最近我遇到了一个问题,我必须找到这样的一套。一个例子可能会帮助:

给出一些清单:

list1 = ['a', 'b']


是否有返回以下集合的函数?

output = {('a', 'b'), ('a', 'a'), ('b', 'b'), ('b', 'a')}


我已经能够使用itertools combinations_with_replacementpermutations函数生成所需的输出,如下所示:

from itertools import combinations_with_replacement, permutations
set1 = set(combinations_with_replacement(['a', 'b'], 2))
set2 = set(permutations(['a', 'b'], 2))

>>> set1
{('a', 'b'), ('a', 'a'), ('b', 'b')}
>>> set2
{('b', 'a'), ('a', 'b')}

set1.update(set2)

>>> set1
{('a', 'b'), ('a', 'a'), ('b', 'b'), ('b', 'a')}


有这样一套的名字吗?我可以使用其他方法吗?

最佳答案

您要itertools.product

>>> import itertools
>>> set(itertools.product(list1, repeat=2))
{('a', 'b'), ('b', 'a'), ('b', 'b'), ('a', 'a')}


带有itertools.product参数的repeat本质上是“ permutations_with_replacement”,这似乎是您想要的。

10-06 05:08
查看更多