我希望将列表中的一个元素与另一个元素进行比较。我实现了我的目标,但它不是一个编写良好的代码。请查看我的代码并给出一些建议。顺便提一下我还有其他一些问题
players_list = ( {'player_name': 'Tom',
'player_flag': 'is_human',
'player_decision': None,
'player_points': 1}
{'player_name': 'Peter',
'player_flag': 'is_computer',
'player_decision': None,
'player_points': 2}
{'player_name': 'John',
'player_flag': 'is_computer',
'player_decision': None,
'player_points': 0.5}
{'player_name': 'Greg',
'player_flag': 'is_computer',
'player_decision': None,
'player_points': 2}
)
players_list = sorted(players_list, key = lambda k: k['player_points'], reverse = True)) #(1)
iterator = 0 #(2)
while players_list[iterator]['player_points'] == players_list[iterator + 1]['player_points']:
iterator += 1
print(' >> The Winner Is...', end = ' ')
if iterator == 0:
print(players_list[0]['player_name'].upper(), '!!!') #(3)
elif iterator > 0:
print('There Is a Draw Between ', end = '')
for j in range (0, iterator + 1):
print(players_list[j]['player_name'], end = ', ') # (4))
print() # (5)
(1):在这种情况下,通过字典值对列表进行排序是最好的方式吗?
(2):我的想法是比较以解决问题。你能否提出自己的意见,如果需要的话,请提出更好的解决方案吗?
(3):在这种情况下,什么样的印刷方式是最多的' pythonic'?
print(players_list[0]['player_name'].upper(), '!!!') # 1
print(%s!!! (players_list[0]['player_name'].upper())) # 2
print({player_name}!!!.format(player_name = players_list[0] ['player_name']).upper()) # 3
(4):如何在没有',#39;的情况下在一行中显示玩家列表在末尾?
print(players_list[j]['player_name'], end = ', ')
>> Peter, Greg, Tom, John,
(5)我使用空白的打印()来显示' / n'在一行显示球员后。有更好的解决方案吗?
非常感谢
答案 0 :(得分:1)
当所有玩家拥有相同的分数时,您的代码会失败。
在任何情况下,您都不需要也不想要对列表进行排序。您想要扫描它,寻找具有最大点数的元素。
未经测试的代码:
winners = None
winner_points = None
for p in players_list:
points = p['player_points']
if winner_points is None or winner_points < points:
winners = [p]
winner_points = points
elif winner_points == points:
winners.append(p)
if not winners:
print("Nobody played today!")
elif len(winners) == 1:
print("The winner is", winners[0]['player_name'])
else:
print("There is a draw between %d players: %s" % (len(winners), ", ".join(p['player_name'] for p in winners))
另外,编码风格:
player_XXX
。 player['XXX']
更具可读性。使用对象,即player.XXX
,甚至更多。