[英]Indexing a list of permutations in Python
這段代碼生成所有排列的列表:
def permute(xs, low=0):
if low + 1 >= len(xs):
yield xs
else:
for p in permute(xs, low + 1):
yield p
for i in range(low + 1, len(xs)):
xs[low], xs[i] = xs[i], xs[low]
for p in permute(xs, low + 1):
yield p
xs[low], xs[i] = xs[i], xs[low]
for p in permute(['A', 'B', 'C', 'D']):
print p
我想為排列列表創建一個索引,這樣,如果我撥打電話號碼,便可以訪問該特定排列。
例如:
if index.value == 0:
print index.value # ['A','B','C','D']
elif index.value == 1:
print index.value # ['A','B','D','C']
#...
我是Python的新手,在此先感謝您提供的任何指導。
您還可以創建一個新函數getperm
以從生成器中獲取排列index
:
def getperm(index,generator):
aux=0
for j in generator:
if aux == index:
return j
else:
aux = aux +1
In: getperm(15,permute(['A', 'B', 'C', 'D']))
Out: ['C', 'A', 'D', 'B']
迭代器不支持“隨機訪問”。 您需要將結果轉換為列表:
perms = list(permute([....]))
perms[index]
就像萊維說的那樣,聽起來像您想使用字典。 該詞典將如下所示:
#permDict = {0:['A', 'B', 'C', 'D'], 1:['A', 'B', 'D', 'C'], ...}
permDict = {}
index = 0
for p in permute(['A', 'B', 'C', 'D']):
permDict[index] = p
index += 1
然后只需根據您分配的鍵獲取一個值。
if index == 0:
print permDict[0] # ['A','B','C','D']
elif index == 1:
print permDict[1] # ['A','B','D','C']
#...
或者只是將每個排列存儲在列表中,然后調用這些索引。
permList = [p for p in permute(['A', 'B', 'C', 'D'])]
#permList[0] = ['A', 'B', 'C', 'D']
#permlist[1] = ['A', 'B','D', 'C']
您可以直接生成所需的排列(無需遍歷所有先前的排列):
from math import factorial
def permutation(xs, n):
"""
Return the n'th permutation of xs (counting from 0)
"""
xs = list(xs)
len_ = len(xs)
base = factorial(len_)
assert n < base, "n is too high ({} >= {})".format(n, base)
for i in range(len_ - 1):
base //= len_ - i
offset = n // base
if offset:
# rotate selected value into position
xs[i+1:i+offset+1], xs[i] = xs[i:i+offset], xs[i+offset]
n %= base
return xs
然后
>>> permutation(['A', 'B', 'C', 'D'], 15)
['C', 'B', 'D', 'A']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.