我已经设计了这个python纸牌游戏,我想知道是否有更好的方法来计算每个玩家的分数而不使用枚举选项。我只有几周才对Coding / Python陌生。只知道基础知识。我的朋友帮了我这个忙。
def select_winner(players_scores, player_names):
max = 0
winner = ''
print('The game scores are:')
for index, score in enumerate(players_scores):
current_player = player_names[index]
print(current_player, "=", score)
if score > max:
max = score
winner = current_player
print("The winner is:", winner)
是否有更简单的方法可以做到,这将帮助我更好/更轻松地理解它。
答案 0 :(得分:0)
如果您真的不想使用枚举,请使用zip:
for current_player, score in zip(player_names, player_scores):
print(current_player)
print(score)
<etc>
zip可让您以相同顺序一次遍历两个列表。
但是,您也可以只使用Python的max函数来找到最高分。
答案 1 :(得分:0)
如果只想找到最好的分数,减少行数的简单方法是使用标准python库中包含的index()和max()方法。您必须考虑的一个极端情况是,如果两个人的最大分数相同,会发生什么情况。
def select_winner(players_scores, player_names):
index_of_max = players_scores.index(max(players_scores))
print('The winner is:', players_names[index_of_max],
'with a score of', players_scores[index_of_max])
如果您也绝对想列出所有分数,则应使用方便的zip()函数,该函数可让您一次访问多个可迭代项。例如:
list1 = (1, 2, 3)
list2 = ('a', 'b', 'c')
for a, b in zip(list1, list2):
print(a, b)
答案 2 :(得分:0)
您可以创建一个字典,其中以玩家名称为键,其得分为值,而不是遍历所有玩家。因为我们现在处于末日状态,所以速度可能并不太重要。
代码如下:
def select_winner(players_scores, player_names):
print('The game scores are:')
# This creates the dictionary of the players
players = dict(zip(player_names, player_scores))
# order based on the score
ordered = sorted(players.items(), key=lambda player: player[1])
# last one in the sorted list (largest score)
winner_name, winner_score = ordered[-1]
print(
"The winner is:", winner_name,
"with an astounding", winner_score, "points!",
)
players
类似于:
{
"Gee": 10,
"Vye": 40,
"Tor": 20,
"Kat": 30,
}
获取字典的.items()
会返回一堆2元组,例如("Gee", 10)
。 (实际上,它们返回一个迭代器,但是现在还太先进了。)
ordered
列表将类似于:
[
("Gee", 10),
("Tor", 20),
("Kat", 30),
("Vye", 40),
]
通过采用最后的元组("Vye", 40)
,我们可以获得获胜者的姓名和分数。放置winner_name, winner_score = ("Vye", 40)
与winner_name = ("Vye", 40)[0]; winner_score = ("Vye", 40)[1]
相同。
希望您能理解所有这一切。如果没有,请评论该问题。否则,请编码!