[英]Get all possible permutations of lists from a single list without duplicates
[英]How to get a list of possible permutations from a dictionary of lists
我需要從這樣的列表字典中獲得一個 output 像 X、Y、W avg # is x
dict = {
'X': [65, 86, 54],
'W': [87, 99, 57],
'Y': [83, 82, 84]
}
output 應該是值列表中可能的排列具有最高平均值,以及實現該值所需的鍵順序,每個鍵只能使用一次。
我嘗試了一些解決方案,但根本沒有任何效果。
這是我到目前為止所擁有的,
list = []
for element in zip(dict, *dict.values()):
list.append(element)
這只是創建一個列表列表,其中鍵是列表的開頭,然后是每個值中的所有數字作為列表的新條目,例如:X,65,86,54 現在我需要找到每個可能的排列三個鍵:值對,其中每個值中的列表組合在一起以找到具有最高平均值的路線,例如 87、86、84
dictt = {
'X': [65, 86, 54],
'W': [87, 99, 57],
'Y': [83, 82, 84]
}
perm = [max([(key,value) for value in lst],key= lambda i : i[1])for key,lst in dictt.items()]
print(perm)
>>> [('X', 86), ('W', 99), ('Y', 84)]
這一行[(key,value) for value in lst])for key,lst in dictt.items()
返回一個列表列表,其中所有值與其鍵配對,所以
[[('X', 65), ('X', 86), ('X', 54)],
[('W', 87), ('W', 99), ('W', 57)],
[('Y', 83), ('Y', 82), ('Y', 84)]]
然后我使用max
和key= lambda i: i[1]
通過使用元組中的第二個元素獲得最大數量,在這種情況下是數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.