【问题标题】:Counting the number of wins for teams in a nested list计算嵌套列表中团队的获胜次数
【发布时间】:2017-05-11 03:41:04
【问题描述】:

我编写了一些代码,我尝试使用这些代码来计算一支足球队赢得一场比赛的次数。比赛被放置在一个嵌套列表中,其中每个子列表分别包含两支球队的名称和他们的比赛得分。

L = [['Patriots', 'Giants', '3', '1'], ['Steelers', 'Patriots', '1', 2'], ['Giants', 'Steelers', '3', '5']]

但是该列表要大得多,并且包含更多参加比赛的足球队。

我已经有一个最终列表,其中包含每支球队的名称以及他们参加过的比赛的数量,这是我计算成功的。

finalList = [['Patriots', 7], ['Giants', 3], ['Steelers', 8]]

我希望输出是这样的:

finalList = [['Patriots', 7, 2], ['Giants', 3, 0], ['Steelers', 8, 1]]

因为爱国者队打了 7 场比赛赢了两场,巨人队打了 3 场比赛赢了零场,钢人队打了 8 场比赛赢了一场。

到目前为止,这是我的代码,它没有给我一些匹配的正确结果。它也不会对计数求和,所以它只是像这样附加一些 1 和 0:

[['Giants', 5, 1, 0, 1]]

我的代码:

for i in L:
    countLeft = 0
    countRight = 0
    if i[2]>i[3]:
        countLeft += 1
    elif i[3]>i[2]:
        countRight += 1
        for k in finalList:
            if i[0]==k[0]:
                k.append(countLeft)
            elif i[1]==k[0]:
                k.append(countRight)
print(finalList)

我也不允许在我的代码中使用任何字典!!

【问题讨论】:

    标签: python list count nested


    【解决方案1】:

    尝试以下方法:

    for k in finalList:
        k.append(0)
    
    for i in L:
        if int(i[2]) > int(i[3]):
                for k in finalList:
                        if k[0] == i[0]:
                                k[2]+=1
        elif int(i[3]) > int(i[2]):
                for k in finalList:
                        if k[0] == i[1]:
                                k[2]+=1
    

    >>> finalList
    [['Patriots', 7, 2], ['Giants', 3, 0], ['Steelers', 8, 1]]
    >>> 
    

    【讨论】:

    • 是的!这工作得很好。我能问一下你为什么输入if len(k) < 3:
    • @BillyWhales 这是为了防止调用k[2]时出现IndexError;本质上,如果团队之前没有获胜,那么数组将只有 2 个索引长 (['Patriots', 7]),所以 k[2] 会引发错误。
    • 我怎样才能编辑这个,如果一支球队赢了 0 场比赛,它只会追加 0 场比赛?
    • 太棒了!非常感谢!
    【解决方案2】:

    您可以使用collections 模块中的Counter 并使用list comprehension 来获得您想要的结果,如下例所示:

    from collections import Counter
    
    a = [['Patriots', 'Giants', '3', '1'], ['Steelers', 'Patriots', '1', '2'], ['Giants', 'Steelers', '3', '5']]
    b = [['Patriots', 7], ['Giants', 3], ['Steelers', 8]]
    
    wins = Counter(team1 if int(team1_s) > int(team2_s) else team2 if int(team2_s) > int(team1_s) else None for team1, team2, team1_s, team2_s in a)
    
    final = final = [[k,l,c[k]] if k in wins else [k,l,0] for k,l in b]
    
    print(final)
    

    输出:

    [['Patriots', 7, 2], ['Giants', 3, 0], ['Steelers', 8, 1]]
    

    【讨论】:

      猜你喜欢
      • 2017-10-09
      • 1970-01-01
      • 2020-08-22
      • 1970-01-01
      • 2019-07-10
      • 2019-06-06
      • 2017-10-06
      • 2012-08-03
      • 1970-01-01
      相关资源
      最近更新 更多