簡體   English   中英

如何在字典中獲取具有最大值的“特定”鍵?

[英]How to get 'specific' keys with maximum value in dictionary?

我的字典是:

rec_Dict = {'000000000500test.0010': -103,
            '000000000500test.0012': -104,
            '000000000501test.0015': -105,
            '000000000501test.0017': -106}

我知道如何找到最大值:

>>print 'max:' + str(max(recB_Dict.iteritems(), key=operator.itemgetter(1)))
max:(u'000000000500test.0010', -103)`

但是我想找到以'000000000501test'開頭的鍵,但不包括'000000000501test.0015'或以'000000000500test'開頭'000000000500test'

它應該像這樣打印:

max:(u'000000000501test.0015', -105)`

如何使用關鍵字獲取?

我無法理解要過濾鍵的條件,但是可以使用以下腳本(只需解決條件)

genetator_filter = genetator_filter = ((a,b) for a,b in rec_Dict.iteritems() if (not '.0015' in a) and (not '000000000500test.' in a) )
#(you need to fix filter conditions for keys)

print 'max:' + str(max(genetator_filter, key = lambda x:x[1]))

分離責任以獲得最終結果,您可以根據要精確匹配的內容找到最高費用。 然后使用該最大值,僅輸出該值。 當然,有些人會認為這不是最優化的方法 ,也不是最實用的方法。 但是,就個人而言,它工作得很好,並以足夠好的性能實現了結果。 此外,使其更具可讀性且易於測試。

通過提取鍵並找到最大值,根據所需的字符串部分獲取最大值:

max_key_substr = max(i.split('.')[0] for i in rec_Dict)

使用該max_key_substr迭代並輸出鍵/值對:

for key, value in rec_Dict.items():
    if max_key_substr in key:
        print(key, value)

輸出將是:

000000000501test.0015 -105
000000000501test.0017 -106

您說的那樣打印的內容沒有任何意義,因為根據您所說的其他內容,鍵'000000000501test.0015'應該已經被排除在外。

忽略這一點,您可以使用生成器表達式篩選出不需要處理的項目:

from operator import itemgetter

rec_Dict = {'000000000500test.0010': -103,
            '000000000500test.0012': -104,
            '000000000501test.0015': -105,
            '000000000501test.0017': -106}

def get_max(items):
    def sift(record):
        key, value = record
        return key.startswith('000000000501') and not key.endswith('.0015')

    max_record = max((item for item in items if sift(item)), key=itemgetter(1))
    return max_record

print(get_max(rec_Dict.iteritems()))  # -> ('000000000501test.0017', -106)

暫無
暫無

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

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