如何在 Python 中获取列表的所有排序排列



给定一个列表,我想要一定长度的所有排列,但只想要那些保持排序的排列。

因此,如果列表是

[1,1,3,4]

那么长度为 2 的答案是

 [[1,1], [1,1], [1,3], [1,3] [3,4], [1,4], [1,4]]

请提供有效的答案。

import itertools
l = [1, 1, 3, 4]
r = [perm for perm in itertools.permutations(l, 2) if sorted(perm) == list(perm)]

结果在:

[(1, 1), (1, 3), (1, 4), (1, 1), (1, 3), (1, 4), (3, 4)]

如果您希望结果排序且唯一

s = sorted(set(r))  #  [(1, 1), (1, 3), (1, 4), (3, 4)]

如果您希望结果作为列表而不是元组,只需将它们转换为list()


使用itertools.permutations的食谱,我为您制作了这个便利功能:

def sorted_perms(iterable, r=None):
    pool = tuple(sorted(iterable))
    n = len(pool)
    r = n if r is None else r
    for indices in itertools.product(range(n), repeat=r):
        if len(set(indices)) == r and tuple_is_sorted(indices):
            yield tuple(pool[i] for i in indices)
memo = {}  # simple memoization for efficiency.
def tuple_is_sorted(t):
    return memo.setdefault(t, bool(sorted(t) == list(t)))
r = list(sorted_perms(l, 2))  #  [(1, 1), (1, 3), (1, 4), (1, 3), (1, 4), (3, 4)]
s = sorted(set(r))  #  [(1, 1), (1, 3), (1, 4), (3, 4)]
您可以使用

itertools.permutations 和 operator.le 来过滤

import itertools
import operator
l = [1, 1, 3, 4]
unique = filter(lambda x: operator.le(x[0], x[1]), itertools.permutations(l, 2))
print(sorted(unique))

输出

[(1, 1), (1, 1), (1, 3), (1, 3), (1, 4), (1, 4), (3, 4)]

将其转换为列表

print([[a, b] for a, b in sorted(unique)])

输出

[[1, 1], [1, 1], [1, 3], [1, 3], [1, 4], [1, 4], [3, 4]]

itertools.permutation 对你来说是一个非常慢的函数。

>>> a = [5, 3,4,1]
>>> b = sorted(range(len(a)), key = lambda i: a[i])
>>> perm = [ (a[i], b[i]) for i in range(len(b))]
>>> perm
[(3, 5), (1, 3), (2, 4), (0, 1)]

最新更新