【问题标题】:Find highest score and print找到最高分并打印
【发布时间】:2021-01-06 22:26:51
【问题描述】:

我正在用 Python 完成一项学校作业,并制作了一个“飞镖游戏”,您可以在其中选择玩家数量和每个玩家的投掷次数。分数是随机给的。

我想总结每个玩家的得分并宣布获胜者。我已经到了求和部分,但不知道如何宣布正确的获胜者。现在每个人都是赢家,这很好,但并不正确。

关于我应该如何解决这个问题的任何想法?

import random                                   
player = int(input("How many players? "))         
throws = int(input("How many throws per player? "))            
score_list = []

                                                
for i in range(player):                    
    player_score = []                           
    for j in range(throws):                
        score = random.randrange(1, 50)        
        player_score.append(score)             
    score_list.append(player_score)             
                                                
i = 0                                           
j = 0

for i in range(player):                                    
    print("Player " + str(i + 1) + " got these points: ")    
    for j in range(throws):
        print(str(score_list[i][j]))                             

i = 0
j = 0

for i in range(player):
    sum = 0
    biggest_sum = 0
    for j in range(throws):
        sum += score_list[i][j]
    print(f"Player {i+1} got {sum} points in total")
    if sum >= biggest_sum:
        biggest_sum = sum
        print(f"Player {i+1} got the most points and won!")

【问题讨论】:

  • 你不仅要记住最大的数,还要记住拥有它的玩家(号码)。然后打印 after 循环结束

标签: python list


【解决方案1】:

一些思考的食物:

scores = [
    [1, 2, 3],
    [5, 6, 0],
    [2, 4, 4]
]

max_score = max(scores, key=sum)
winning_player = scores.index(max_score) + 1

print(f"Player #{winning_player} is the winner, with {sum(max_score)} points!")

输出:

Player #2 is the winner, with 11 points!
>>> 

【讨论】:

  • 谢谢。保持正确的索引对我来说是一项艰巨的任务,但这是一个很好的方法!
  • 不客气。然而,这样做的一个副作用是,如果两个玩家的分数相同(分数列表相同,相同索引处的值相同),那么首先出现在列表中的玩家将被选为获胜者。跨度>
【解决方案2】:

您可以使用列表推导:

score_list = [[9, 4, 35], [2, 32, 45]]
sc1 = [sum(x) for x in score_list] #sum sub-list and get the maximum value of the resultant list        
print(f'Player {sc1.index(max(sc1))+1} wins with a score of {max(sc1)}')

【讨论】:

  • 别忘了他还需要最大行总和的索引才能知道哪个玩家赢了……所以基本上是this
猜你喜欢
  • 2021-05-08
  • 1970-01-01
  • 2017-02-08
  • 1970-01-01
  • 2022-06-12
  • 2020-05-10
  • 1970-01-01
  • 2019-09-03
  • 1970-01-01
相关资源
最近更新 更多