[英]Removing elements from a dictionary consisting of tuples calculating the last element in the tuple and the value in the dictionary
給出以下字典:
a = {('a','b', 'c'):3,('a','d','c'):4, ('f','e','b'):5, ('r','t','b'):5.1}
字典由作為鍵的元組和作為值的數字組成。 每個元組由一系列字母組成。 從最后一個元素相同的所有元組中,應該排除那些字典值最低的元組。 例如元組('a','b', 'c')
和元組('a','d','c')
都將字母C
作為最后一個元素,因此其值為最低的應該被刪除。 參考上面的字典,結果應該是:
{('a','d','c'):4, ('r','t','b'):5.1}
你可以這樣做:
from collections import defaultdict
from operator import itemgetter
a = {('a','b', 'c'):3,('a','d','c'):4, ('f','e','b'):5, ('r','t','b'):5.1}
# group the items by the last element of the key of the tuple
lookup = defaultdict(list)
for key, value in a.items():
lookup[key[2]].append((key, value))
# find the maximum in each group by the value of the tuple
result = dict(max(value, key=itemgetter(1)) for value in lookup.values())
print(result)
Output
{('a', 'd', 'c'): 4, ('r', 't', 'b'): 5.1}
代碼:
a = {('a','b', 'c'):3,('a','d','c'):4, ('f','e','b'):5, ('r','t','b'):5.1}
keys_to_remove = []
for key in a.keys():
srch_key = key[-1]
lowest_val = min(v for k,v in a.items() if k[-1] == srch_key)
keys_to_remove.append(*(k for k,v in a.items() if k[-1] == srch_key and v == lowest_val))
for key_to_remove in set(keys_to_remove):
a.pop(key_to_remove)
print(a)
Output:
{('a', 'd', 'c'): 4, ('r', 't', 'b'): 5.1}
另一個解決方案可能是:
a_dict = {('a','b', 'c'):3,('a','d','c'):4, ('f','e','b'):5, ('r','t','b'):5.1}
b_dict = dict()
seq = 2
for key in a_dict:
b_key = find_key(b_dict, key[seq])
if b_key is not None:
b_dict.pop(b_key)
b_dict[key] = a_dict[key]
else:
b_dict[key] = a_dict[key]
def find_key(x_dict, k, seq=2):
for key in x_dict:
if key[seq] == k:
return key
return None
創建一個空字典。 遍歷字典,在新字典中搜索關鍵元組的最后一個元素。 如果不存在,則將鍵:值添加到新字典。 如果找到任何,請檢查其值是否更大。 如果不是,則刪除該元素並添加新的鍵:值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.