大家好,我有一个关于根据字典中的项目数打印最大值到最小值的问题。
我需要一个完整的密钥列表,上面印有密钥旁边显示的次数。
基于这两个列表:
Teams = ['Boston Americans','World Series Not Played in 1904','New York Giants',
'Chicago White Sox','Chicago Cubs','Chicago Cubs','Pittsburgh Pirates',
'Philadelphia Athletics']
Year = [1903,1904,1905,1906,1907,1908,1909,1910]
如何根据每个团队拥有的项目数量打印以下内容:
D = {Teams,Year}
我忘了提到我正在从 txt 文件中读取这个。
更新
def Team_data(team,year):
D = defaultdict(list)
for team,year in zip(team,year):
D[team].append(year)
pprint(D)
return D
然后它将返回:
D = {'Boston Americans':1903,'World Series Not Played in 1904':1904,
'New York Giants':1905,'Chicago White Sox': 1906,'Chicago Cubs': 1907,
'Chicago Cubs':1908,'Pittsburgh Pirates':1909,'Philadelphia Athletics':1910}
Team_max = []
打印时,我在列表中得到以下内容
Chicago Cubs, 2
Boston Americans, 1
World Series Not Played in 1904, 1
New York Giants, 1
Chicago White Sox, 1
Pittsburgh Pirates, 1
Philadelphia Athletics, 1
我正试图从制作
团队 = 关键和年份 = 价值
Chicago Cubs:[1907,1908]
团队 = 键和显示次数 = 值
Chicago Cubs:[2]
我根据阅读的内容尝试使用以下内容:
def Team_data_max(D):
key = D.keys()
value = D.values()
team_max = []
team_max = sorted(D, key=lambda key: len(D[key]))
print(team_max)
#Print 1 Key based and 1 max number of items in dictionary
#Chicago Cubs, 2
或者这个
team_max = []
team_max = max(((k, len(v)) for k, v in D.items()), key=lambda x: x[1])
print(Series_max)
#Print the entire key list least to greatest without a number which is what I need
#based on the items list
然后这个
s = []
s = [k for k in D.keys() if len(D.get(k))==max([len(n) for n in D.values()])]
print(s)
#print max key without number
#Chicago Cubs
虽然我在第二个函数中更接近了,但我只需要这个数字。关于如何解决这个问题的任何想法?任何想法或指导表示赞赏。