【问题标题】:Python Comparing lists averages sortingPython比较列表平均排序
【发布时间】:2013-05-07 01:38:01
【问题描述】:

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

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

(如果我的解释很糟糕且难以理解,对于团队 A,百分比计算为 (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。

【问题讨论】:

    标签: python list sorting python-2.7 average


    【解决方案1】:

    你可以在这里使用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]]
    

    【讨论】:

    • 效果很好!谢谢你,阿什维尼。虽然,如果我可能会问,key 和 zip 究竟在这里做什么?我以前从未见过这些关键字。
    • @Gabe 在docs 上查看一些 zip 的示例。 key 用于告诉排序函数使用什么值来比较项目,所以这里我使用每个列表中的第二个项目进行比较。 docs.python.org/2/howto/sorting.html
    • 啊,这对当时发生的事情来说是有道理的。非常感谢。
    猜你喜欢
    • 2012-07-25
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多