Svi*_*the 2 python combinations permutation
我不相信以前有人问过这个确切的问题。我最近遇到了一个问题,我必须找到这样一个集合。一个例子可能会有所帮助:-
给出一些列表:
list1 = ['a', 'b']
Run Code Online (Sandbox Code Playgroud)
是否有返回以下集合的函数?
output = {('a', 'b'), ('a', 'a'), ('b', 'b'), ('b', 'a')}
Run Code Online (Sandbox Code Playgroud)
我已经能够使用itertools
combinations_with_replacement
和permutations
函数生成所需的输出,如下所示:
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')}
Run Code Online (Sandbox Code Playgroud)
有这样一套的名字吗?有没有我可以使用的替代方法?
你想要itertools.product
:
>>> import itertools
>>> set(itertools.product(list1, repeat=2))
{('a', 'b'), ('b', 'a'), ('b', 'b'), ('a', 'a')}
Run Code Online (Sandbox Code Playgroud)
itertools.product
与repeat
参数基本上是“ permutations_with_replacement
”,这似乎是你想要的。