Python找到了一个拥有最多;“赢”;列表中
我需要一些帮助,试图找出一个快速算法,我正在努力编写。基本上,我有一个如下列表:Python找到了一个拥有最多;“赢”;列表中,python,list,Python,List,我需要一些帮助,试图找出一个快速算法,我正在努力编写。基本上,我有一个如下列表: season = [[['P1', '3', 'P2', '4'], ['P3', '2', 'P4', '1'], ['P1', '2', 'P3', '5'], ['P4', '2', 'P1', '3']]] 每个嵌套列表表示玩家之间游戏中的分数,该列表中有更多的嵌套列表,这些列表采用与上面所示相同的格式,玩家最多可得到32个 我想做的是编写一个算法,让我能够显示名单中获胜最多的球员
season = [[['P1', '3', 'P2', '4'], ['P3', '2', 'P4', '1'],
['P1', '2', 'P3', '5'], ['P4', '2', 'P1', '3']]]
每个嵌套列表表示玩家之间游戏中的分数,该列表中有更多的嵌套列表,这些列表采用与上面所示相同的格式,玩家最多可得到32个
我想做的是编写一个算法,让我能够显示名单中获胜最多的球员,以及他们取得的胜利数量,我正在努力找出如何做到这一点,因此,任何帮助都将不胜感激
以下是我目前的情况:
count = 0
for matchScores in season:
for scores in matchScores:
playerName = score[0]
if playerName and score[1] > score[3]
count = count + 1
“季节”列表由以下人员创建:
season = []
season.append(tournament1)
season.append(tournament2)
season.append(tournament3)
etc以下是一种将胜利与每位玩家联系起来的方法: 代码:
你可以这样做
player_with_most_wins = max(scores, key=scores.get)
print(player_with_most_wins + " has " + str(scores[player_with_most_wins]) + " wins")
代码
scores = dict()
for match in season:
for score in match:
if int(score[1]) > int(score[3]):
if score[0] not in scores:
scores[score[0]] = 0
scores[score[0]] += 1
elif int(score[1]) < int(score[3]):
if score[2] not in scores:
scores[score[2]] = 0
scores[score[2]] += 1
print(scores)
这将为您提供一本所有玩家及其分数的字典。从那里,你可以做这样的事情
player_with_most_wins = max(scores, key=scores.get)
print(player_with_most_wins + " has " + str(scores[player_with_most_wins]) + " wins")
要打印出获胜次数最多的玩家,以及他们的获胜次数,请按如下所示:
P3 has 2 wins
请包括你的代码。让我们看看你到目前为止做了什么!另外,请解释为什么你有一个列表列表,但是第二个最内部的列表只有一个元素,一个分数列表。为什么不列出一个列表呢?这主要是因为列表是如何创建的,每个列表中的分数都来自不同的列表,并存储在一个列表中,我将编辑我的原始帖子,以显示列表是如何创建的。在迭代所有比赛时,使用a
dict
跟踪每位球员的获胜次数。提示:n_wins=defaultdict(int)
(来自collections
),内部循环+逻辑:n_wins[winner]+=1
太棒了,这正是我想要做的!非常感谢
player_with_most_wins = max(scores, key=scores.get)
print(player_with_most_wins + " has " + str(scores[player_with_most_wins]) + " wins")
P3 has 2 wins