需要在前两个元素之后用顺序排列列表
Need to permute list with order mattering after first two elements
假设l = ['a', 'b', 'c', 'd']
...
我需要从该列表中生成以下 combinations/permutations(通常,该列表可以包含更多元素):
['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
和 itertools
中的 combinations
的各种组合,但都没有成功(我不敢 post 我的代码,因为害怕尴尬)。
使用现有的itertools
库函数最直接的解决方案是select将前两个元素作为组合,然后将其余元素作为剩余元素的排列:
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')
假设l = ['a', 'b', 'c', 'd']
...
我需要从该列表中生成以下 combinations/permutations(通常,该列表可以包含更多元素):
['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
和 itertools
中的 combinations
的各种组合,但都没有成功(我不敢 post 我的代码,因为害怕尴尬)。
使用现有的itertools
库函数最直接的解决方案是select将前两个元素作为组合,然后将其余元素作为剩余元素的排列:
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')