小编Svi*_*the的帖子

是否有一个 Python 函数可以找到列表的所有 k 长度排序?

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

给出一些列表:

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_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')}
Run Code Online (Sandbox Code Playgroud)

有这样一套的名字吗?有没有我可以使用的替代方法?

python combinations permutation

2
推荐指数
1
解决办法
39
查看次数

标签 统计

combinations ×1

permutation ×1

python ×1