需要在前两个元素之后排列顺序重要的列表

问题描述 投票:-1回答:1

假设l = ['a', 'b', 'c', 'd'] ...

我需要从此列表中生成以下组合/排列(通常,该列表可能包含更多元素):

['a', 'b', 'c', 'd']
['a', 'b', 'd', 'c']
['a', 'c', 'b', 'd']
['a', 'c', 'd', 'b']
['a', 'd', 'b', 'c']
['a', 'd', 'c', 'b']
['b', 'c', 'a', 'd']
['b', 'c', 'd', 'a']
['b', 'd', 'a', 'c']
['b', 'd', 'c', 'a']
['c', 'd', 'a', 'b']
['c', 'd', 'b', 'a']

因此,对于列表顺序的前两个位置没有关系,尽管我需要采用列表元素的所有组合,而在列表的后两个位置(或n)则很重要。我已经尝试过使用permutations中的combinationsitertools的各种组合,但都没有成功(我不敢发布自己的代码,以免感到尴尬)。

python itertools combinatorics
1个回答
1
投票

使用现有itertools库函数的最直接的解决方案是选择前两个元素作为组合,然后选择其余两个元素作为其余元素的排列:

import itertools

def partly_unordered_permutations(lst, k):
    elems = set(lst)
    for c in itertools.combinations(lst, k):
        for d in itertools.permutations(elems - set(c)):
            yield c + d

用法:

>>> for p in partly_unordered_permutations('abcd', 2):
...     print(p)
... 
('a', 'b', 'c', 'd')
('a', 'b', 'd', 'c')
('a', 'c', 'b', 'd')
('a', 'c', 'd', 'b')
('a', 'd', 'b', 'c')
('a', 'd', 'c', 'b')
('b', 'c', 'a', 'd')
('b', 'c', 'd', 'a')
('b', 'd', 'a', 'c')
('b', 'd', 'c', 'a')
('c', 'd', 'a', 'b')
('c', 'd', 'b', 'a')
© www.soinside.com 2019 - 2024. All rights reserved.