繁体   English   中英

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

[英]All permutations in adjacent elements of list

我这样做:

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))

采取所有可能的排列方式,但在拼合的列表中,其中每对相邻元素对应于一个排列。

这给出:

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

其中此列表中的相邻元素对都是所有排列:

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

而不是带有排列的经典元组列表:

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

有没有比我的代码更简洁和/或更快速的方法或功能呢?

您正在调用组合函数而不是排列。 尝试这个

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