【发布时间】:2016-11-14 02:57:56
【问题描述】:
我正在编写一个遍历字典的函数。字典包含艺术家作为键和他们的画作为值。我需要在面积最大的字典中找到这幅画,如果有两个面积相等,则应将它们作为元组列表返回。
示例字典:
{
'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 和“二十”画的 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(matches) 但我意识到这并没有做太多,除非该函数将长度和宽度相乘然后查找最大值。如果有人有建议会很有帮助
【问题讨论】:
-
你可以传递
max一个key参数:max(lst, key=lambda tupl: tupl[2]*tupl[3])会从你的字典中的一个列表中得到面积最大的元组。 -
感谢您的建议,我应该用这个代替 max(matches) 吗?
-
这将更适合该代码中的
max(the_list),但即使多个项目共享最大值,max 通常也只会返回一个项目 -
谢谢我添加了你的建议我会测试看看这个函数现在做了什么
标签: python python-3.x dictionary max area