简体   繁体   English

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

[英]How to get all sorted permutations of a list in Python

Given a list, I want all the permutations of a certain length, but only those that remain sorted. 给定一个列表,我想要一定长度的所有排列,但只保留那些排序的排列。

So if the list is 所以如果列表是

[1,1,3,4]

then the answer with length 2 is 那么长度为2的答案是

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

Please provide an efficient answer. 请提供有效的答案。

import itertools

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

results in: 结果是:

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

If you want the results sorted, and unique: 如果要对结果进行排序并且唯一:

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

If you want the results as lists instead of tuples, just cast them as list() 如果您希望将结果作为列表而不是元组,只需将其转换为list()


Using the recipe for itertools.permutations I made this convenience function for you: 使用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)]

You can use itertools.permutations and operator.le to filter 您可以使用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))

Output 输出量

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

Transform it to lists 将其转换为列表

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

Output 输出量

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

itertools.permutation is very slow function for you. 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)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM