我正在编写一个函数,我会通过字典。字典包含艺术家作为键,他们的绘画作为价值。我需要在具有最大区域的字典中找到该绘画,如果有两个具有相同区域的绘制,则应将它们作为元组列表返回。
示例词典:
{
'A, Jr.':[("One",1400,10,20.5,"oil paint","Austria"),("Three",1400,100.0,100.0,"oil paint","France"),("Twenty",1410,50.0,200.0,"oil paint","France")],
'X':[("Eight",1460, 100.0, 20.0, "oil paint","France"),("Six",1465,10.0, 23.0, "oil paint", "France"),("Ten",1465,12.0,15.0,"oil paint","Austria"),("Thirty",1466,30.0,30.0,"watercolor","Germany")],
'M':[("One, Two", 1500, 10.0, 10.0, "panel","Germany")]
}
基本上,四位数字是绘画或艺术品创作的年份,接下来的两个数字是长度和宽度。我需要在乘以长度和宽度时返回具有最大面积的值。所以对于上面的字典,函数find_largest应该返回
find_largest(dictionary2())
[('A, Jr.', 'Three'), ('A, Jr.', 'Twenty')]
因为"三" 100 * 100 = 10,000 " Twenty"和#34; Twenty" 50 * 200 = 10,000绘画它们都作为元组返回列表中。
有人有关于如何做到这一点的建议吗?我已经开始使用以下代码,但我认为这不是正确的方法。
def find_largest(dictionary):
matches = {}
for key, the_list in db.items():
for record in the_list:
value = record[4]
if dictionary in record:
if key in matches:
max(the_list)
max(lst, key=lambda tupl: tupl[2]*tupl[3])
matches[key].append(record)
else:
matches[key] = [record]
return matches
这基本上是来自早期函数的代码,只有一些重大更改。这个基本框架适用于我的一些目标。我添加了max(匹配),但我意识到除非函数乘以长度和宽度然后查找最大值,否则不会做太多。如果有人有建议会有帮助
答案 0 :(得分:2)
可能更容易跟踪当前的最大值
data = {
'A, Jr.':[("One",1400,10,20.5,"oil paint","Austria"),("Three",1400,100.0,100.0,"oil paint","France"),("Twenty",1410,50.0,200.0,"oil paint","France")],
'X':[("Eight",1460, 100.0, 20.0, "oil paint","France"),("Six",1465,10.0, 23.0, "oil paint", "France"),("Ten",1465,12.0,15.0,"oil paint","Austria"),("Thirty",1466,30.0,30.0,"watercolor","Germany")],
'M':[("One, Two", 1500, 10.0, 10.0, "panel","Germany")]
}
def find_largest(d):
matches = []
max_value = 0
for key in d:
for record in d[key]:
value = record[2] * record[3]
if value > max_value:
matches = [(key, record[0])]
max_value = value
elif value == max_value:
matches.append((key, record[0]))
return matches
# Output
>>> find_largest(data)
[('A, Jr.', 'Three'), ('A, Jr.', 'Twenty')]