簡體   English   中英

如何獲取字典元組的最大值

[英]How to get the maximum value of a dictionary tuple

我有一個這樣的字典:

dic={(0, 1): 0.059999999999999996,
 (0, 5): 0.13157894736842105,
 (0, 15): 0.23157894736842105,
 (1, 0): 0.049999999999999996,
 (5, 0): 0.13157894736842105,
 (5, 15): 0.049999999999999996,
 (15, 5): 0.23157894736842105}

我想獲得向量的第一個坐標中的每個元素的最大值,以及向量的第二個元素。

The output would be:
For 0 [First coordinate]:      (0, 5): 0.13157894736842105
For 0 [Second coordinate]:      (5, 0): 0.13157894736842105
For 1 [First coordinate]:       (1,0) 0.049999999999999996
For 1 [Second coordinate]:       (0,1) 0.059999999999999996
and so on.

我知道我可以使用這樣的東西

max_keys = [k for k, v in dic.items() if v == max_value] 

但我無法得到正確的方法。

def getMaxForX(number):
    return max([v for k, v in dic.items() if k[0] == number])

def getMaxForY(number):
    return max([v for k, v in dic.items() if k[1] == number])

我不確定如何完全實現這些,但我認為這是你正在尋找的列表理解

例如:

getMaxForX(0) => 0.23157894736842105,
getMaxForY(0) => 0.13157894736842105

如果你想要每個最大值的鍵和值都有一點不同但仍然可行。

這可以在oneliner中完成

例如,對於0 [第一坐標]:

print(max([(k, v) for k, v in filter(lambda x: x[0][0]==y, dic.items())], key=lambda x:x[1]))
Out[2]: ((0, 15), 0.23157894736842105)

但更好的是把它變成一個函數:

def get_max(dic, coord, val):
    return max(filter(lambda item: item[0][coord] == val, dic.items()), key=lambda x: x[1])

對於0 [第一坐標]:

print(get_max(dic, 0, 0))
Out[5]:  ((0, 5), 0.23157894736842105)
# or storing the key and the value:
key_max, value_max = get_max(dic, 0, 0)

對於0 [第二坐標]:

print(get_max(dic, 1, 0))
Out[6]: ((5, 0), 0.13157894736842105)

等等...

希望有幫助和快樂的編碼!

此問題不適合具有元組鍵的字典。 您可以迭代並維護自己的結果字典,以保持每個索引鍵的最大值。 或者您可以使用第三方庫,例如Pandas:

import pandas as pd

dic = {(0, 1): 0.059999999999999996, (0, 5): 0.13157894736842105,
       (0, 15): 0.23157894736842105, (1, 0): 0.049999999999999996,
       (5, 0): 0.13157894736842105, (5, 15): 0.049999999999999996,
       (15, 5): 0.23157894736842105}

df = pd.DataFrame.from_dict(dic, orient='index').reset_index()
df[['key0', 'key1']] = pd.DataFrame(df.pop('index').values.tolist())

res = pd.concat((df.groupby(f'key{i}')[0].max().rename(f'idx{i}')
                 for i in range(2)), axis=1)

print(res)

        idx0      idx1
0   0.231579  0.131579
1   0.050000  0.060000
5   0.131579  0.231579
15  0.231579  0.231579

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM