Beatles_Discography = {"Please Please Me": 1963, "With the Beatles": 1963,"A Hard Day's Night": 1964, "Beatles for Sale": 1964, "Twist and Shout": 1964,"Help": 1965, "Rubber Soul": 1965, "Revolver": 1966,"Sgt. Pepper's Lonely Hearts Club Band": 1967,"Magical Mystery Tour": 1967, "The Beatles": 1968,"Yellow Submarine": 1969 ,'Abbey Road': 1969,"Let It Be": 1970}要求編寫一個函數返回發布最多專輯的年份,調用該函數時應返回1964年這一年相對于其他年份發行的唱片數量較多一些。并如果多個年份的最大發行量相同,則該函數將返回一個年份列表。我寫了一個程序如下:def most_prolific():list=[]for v in Beatles_Discography.values():list.append(v)return max(list,key=list.count)可以返回1964,但后面一個問題就不知道怎樣寫了即如果多個年份的最大發行量相同,則該函數將返回一個年份列表。想了好半天都不知道,想請教各位大神怎樣寫?不勝感激!
1 回答

蕭十郎
TA貢獻1815條經驗 獲得超13個贊
def get_year_count():
result = dict()
for k, v in Beatles_Discography.items():
if result.get(v, None) is None:
result[v] = 1
else:
result[v] += 1
result = sorted(result.iteritems(), lambda x:x[1], reverse=True)
return result
def get_the_most(the_list):
result = list()
temp = 0
for the_tuple in the_list:
if temp == 0:
temp = the_tuple[1]
result.append(the_tuple[0])
elif temp == the_tuple[1]:
result.append(the_tuple[0])
else:
break
return result
if __name__ == "__main__":
the_list = get_year_count()
result = get_the_most(the_list)
print(result)
添加回答
舉報
0/150
提交
取消