给定一个列表,我想要一定长度的所有排列,但只有那些保持排序的排列.
所以,如果列表是
[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)]