我这里有代码:
def most_popular_book(book_loans):
vBL = book_loans.values()
kBL = book_loans.keys()
items = book_loans.items()
print items
kBL = sorted(kBL, key=str.lower)
mvBL = max(vBL)
for key,vaule in items:
if vaule == mvBL:
return key
我使用这段代码的目的是获得值最大的键,如果两个键的值相同,则选择按字典顺序排在第一位的键。你知道吗
现在代码的第一部分工作正常了!但是我对第二部分有困难。 我读了一些关于这个主题的代码,但是我还没有找到一个方法使它工作。你知道吗
代码应如何工作的示例:
print most_popular_book({'harry potter':['yossi','adam'],
'lilo and stich':['yossi', "adam"], 'catch-22':['adam'] })
'harry potter'
(应该是哈利波特) 但我的代码打印出“lilo和stich”
另一个例子:
{'the little prince': ['yossi'], 'harry potter': ['yossi', 'assaf'],
'catch-22': ['yossi', 'dana']}
'catch-22'
(此输出工作正常)
如果你只想要最流行的书,你可以用min:
输出
这个想法与@PatrickArtner的答案相同,唯一的区别是排序的是O(nlogn),min是O(n)。不需要对列表排序,只需找到最小值。你知道吗
您可以通过以下方式获得完全排序的列表:
拿第一个。你知道吗
它的工作原理是定义一个
tuple
作为排序标准-tuples
按第一个值排序,如果第一个值绘制,则按第二个值排序,以此类推按
-len()
排序“反转”它(也可以将reverse=True
参数指定为排序-任何一个都有效。你知道吗输出:
相关问题 更多 >
编程相关推荐