如何在Python

时间:2017-01-11 10:15:50

标签: python list

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

所以如果列表是

[1,1,3,4]

然后长度为2的答案是

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

请提供有效的答案。

3 个答案:

答案 0 :(得分:6)

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)]

答案 1 :(得分:0)

您可以使用itertools.permutationsoperator.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]]

答案 2 :(得分:0)

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)]