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
提交
取消