我目前正在研究一个python问题,涉及一个包含2个数字和标识符的子列表的列表,总共需要三件事。该过程的名称为compareTeams(lstTeams),用于计算多个季节中球队的平均获胜百分比。第一个列表是获胜的游戏,第二个列表是输了的游戏。有问题的程序将列出这些列表,并尝试通过将获胜的游戏总数与总游戏数相加,然后将其除以列表的长度来找到最高的平均值。两个列表的大小相同。然后,它将平均值按从大到小的顺序按列表对进行排序,标识符标记为每个列表中的第一个元素。举个例子:

teamA = [[6, 4, 8, 5, 0], [3, 6, 0, 2, 4], 'A'] avg winning percentage = 0.56


(如果我的解释很差且难以理解,对于teamA,该百分比计算为(6/9 + 4/10 + 8/8 + 5/7 + 0/4)/ 5)

teamB = [[3, 6, 8, 2, 4], [3, 6, 8, 2, 4], 'B'] avg winning percentage = 0.50
teamC = [[3, 6, 8, 2, 4], [0, 0, 0, 0, 0], 'C'] avg winning percentage = 1

compareTeams([teamA, teamB, teamC]) gives [['C', 1],['A', 0.56],['B', 0.50]]


我已经考虑了很多这个问题,但是对于python来说是新手,所以我不确定是否正确调用了所有东西。我正在使用的解释器在运行时甚至不显示我的过程,这使我相信我做错了什么。这是我的代码:

def compareTeams(lstTeams):
  a = 0
  x = 0
  lst = []
  y = lstTeams[a]
  for a in range(0, len(y)):
    x = x + ((float(y[0][0]) / (y[1][0])) / len(y[0]))
    a = a + 1
    lst.append(x)
  return lst.reverse(lst.sort())


它是否正确?我做错什么了吗?任何帮助将不胜感激。

注意:我为此使用python 2.7。

最佳答案

您可以在此处使用zip

def compare_team(teams):
   lis = []
   for team in teams:
       #zip fetches items from the same index one by one from the lists passed to it
       avg = sum( (x*1.0)/(x+y) for x,y in zip(team[0],team[1]))/ len(team[0])
       lis.append([team[-1],avg])

   lis.sort(key = lambda x:x[1],reverse = True) #reverse sort based on the second item
   return lis



>>> compare_team(([teamA, teamB, teamC]))
[['C', 1.0], ['A', 0.5561904761904761], ['B', 0.5]]

10-07 12:59
查看更多