简体   繁体   English

列表的相邻元素中的所有排列

[英]All permutations in adjacent elements of list

I do this: 我这样做:

from itertools import chain, combinations, permutations
import itertools

i = [5, 6, 7]

x = list(combinations(i, 2))

x.append((x[1][0],))

x = list(itertools.chain.from_iterable(x))

to take all the possible permutations but in a flattened list where each pair of adjacent elements corresponds to a permutation. 采取所有可能的排列方式,但在拼合的列表中,其中每对相邻元素对应于一个排列。

This gives: 这给出:

[5, 6, 5, 7, 6, 7, 5]

where the pairs of adjacent elements in this list are all the permutations: 其中此列表中的相邻元素对都是所有排列:

(5,6), (6,5), (5,7), (7,6), (6,7), (7,5) 

instead of the classic list of tuples with permutations: 而不是带有排列的经典元组列表:

[(5, 6), (5, 7), (6, 5), (6, 7), (7, 5), (7, 6)]

Is there any function or way which does this in a more concise and/or quick way than my code? 有没有比我的代码更简洁和/或更快速的方法或功能呢?

You are calling a combination function instead of permutation. 您正在调用组合函数而不是排列。 Try this 尝试这个

from itertools import chain, combinations, permutations
import itertools

i = [5, 6, 7]

x = list(permutations(i, 2))
print(x)

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

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