在字典列表中查找值

时间:2020-06-09 22:41:41

标签: python dictionary

我从受欢迎的大学团队(俄勒冈鸭队)获得的历史得分获得了这份名单:

[
    '1916-10-07,1916,Willamette,97,0\n',
    '1916-10-14,1916,Multnomah A.C.,28,0\n',
    '1916-10-21,1916,California,39,14\n',
    '1916-11-04,1916,Washington,0,0\n',
    '1916-11-11,1916,Washington State,12,3\n',
]

我编写了代码以提取季节,鸭的得分并允许得分并将其放入字典中。

def parse_football_data(lst):

    DUCKS = {
        'season': [int(i.split(',')[1]) for i in lst],
        'scored': [int(i.split(',')[3]) for i in lst],
        'allowed': [int(i.split(',')[4].strip()) for i in lst],
    }
    return DUCKS

具有以下输出:

{'season': [1916, 1916, 1916, 1916, 1916],
 'scored': [97, 28, 39, 0, 12],
 'allowed': [0, 0, 14, 0, 3]}

我现在需要编写一个函数def total_by_year(games, year):,该函数将为我提供输入年份的分数总和,并且对方的团队允许采用以下格式的分数:

total_by_year(dct, 1916)
(51, 17)

当我使用以前的功能输入时:

dct = parse_football_data([
    '1916-10-21,1916,California,39,14\n',
    '1916-11-04,1916,Washington,0,0\n',
    '1916-11-11,1916,Washington State,12,3\n',
    '1917-11-17,1917,California,21,0\n',
    '1917-11-29,1917,Oregon State,7,14\n'
])

如何将年份与字典中的“季节”和“允许”键匹配?

1 个答案:

答案 0 :(得分:1)

这听起来很像作业。尽管如此,请考虑total_by_year()的示例实现。

def total_by_year(dct, year):

  scored = 0
  allowed = 0

  for (index,season) in enumerate( dct['season'] ):
    if season == year:
      scored += dct['scored'][index]
      allowed += dct['allowed'][index]


  return ( scored, allowed )