Python 从由元组组成的字典中删除元素计算元组中的最后一个元素和字典中的值
提供以下词典:Python 从由元组组成的字典中删除元素计算元组中的最后一个元素和字典中的值,python,dictionary,tuples,Python,Dictionary,Tuples,提供以下词典: 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')
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)
输出
{('a', 'd', 'c'): 4, ('r', 't', 'b'): 5.1}
代码:
输出:
{('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
创建一个空字典。迭代dict,在newdict中搜索key元组的最后一个元素。如果不存在,则将key:value添加到newdict。
如果发现,请检查其值是否大于。如果不是,则删除该元素并添加新键:value
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