[英]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.