想知道是否可以為特定串列的所有排列創建一個惰性生成器?我需要一個串列的所有排列[1 ... 2^6]。做類似的事情list(itertools.permutations([i for i in range(1, 2**6)]))對我的電腦來說太多了,所以我想做的是一個懶惰的評估器,它只計算第 i 個排列。
例如,在 haskell 中,這將是某種形式的惰性求值器,但是否可以在 Python 中執行相同的操作?是否也/否則可能是一些已知的演算法來查找我不知道的串列的第 i 次迭代?
uj5u.com熱心網友回復:
兩種方式回答你的問題:
itertools.permutations已經很懶了;它回傳一個生成器,并且只會在您要求的時候評估排列,或者一個一個使用next,或者一次全部使用list,或者在 for 回圈中迭代它,或者其他方式;- 您要求的確切功能在模塊 more_itertools: more_itertools.nth_permutation 中實作。
示范:
from itertools import permutations
from more_itertools import nth_permutation
g = permutations('abc')
print( next(g) )
# ('a', 'b', 'c')
print( next(g) )
# ('a', 'c', 'b')
print( next(g) )
# ('b', 'a', 'c')
print( list(g) ) # will omit the three permutations already extracted with next
# [('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')]
print( nth_permutation('abcdefg', 7, index=16) )
# ('a', 'b', 'c', 'f', 'g', 'd', 'e')
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/380273.html
