[Python]How to sort a string with two variables?
Hello I am somewhat new to python so please bear with me.
My python program has the following lines:
print "Player 1: " +str(player1points)
print "Player 2: " +str(player2points)
print "Player 3: " +str(player3points)
print "Player 4: " +str(player4points)
The player#points are what my program has calculated it to be, so differs everytime I run it.
The result would yield:
Player 1: 3
Player 2: 4
Player 3: 3
Player 4: 5
If possible, I want to sort the result so that each player's points is ranked from highest to lowest first, then the player. If two players are tied for points, then the player with the lowest number will be listed first.
So I expect my resul开发者_开发知识库ts to be like:
Player 4: 5
Player 2: 4
Player 1: 3
Player 3: 3
Any help would be much appreciated!!
Look at the examples of
http://wiki.python.org/moin/HowTo/Sorting#Operator_Module_Functions
If you already have player objects or dictionaries, you could sort with:
players.sort(key=lambda player: player.score, reverse=True)
If not, process your array and split at each ':'
Sample:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def main():
"entry point"
player_strings = ['Player 1:3', 'Player 2:4', 'Player 3:3', 'Player 4:5']
players = []
for player_string in player_strings:
name, score = player_string.split(':')
players.append({'name':name, 'score':score})
players.sort(key=lambda player: int(player['score']), reverse=True)
for player in players:
print ('%s has a score of %s' % (player['name'], player['score']))
if __name__ == '__main__':
main()
sorted(values, key=lambda s: s.split(': ')[1], reverse=True)
Passing a "key function" to the list.sort method allows you to customize how it is sorted.
def sort_players(players):
r"""Sort the players by points.
>>> print sort_players('Player 1: 3\n'
... '\n'
... 'Player 2: 4\n'
... '\n'
... 'Player 3: 3\n'
... '\n'
... 'Player 4: 5\n')
Player 4: 5
Player 2: 4
Player 1: 3
Player 3: 3
"""
# split into a list
players = players.split("\n")
# filter out empty lines
players = [player for player in players if player != '']
def points(player_report):
"""Parse the number of points won by a player from a player report.
A "player report" is a string like 'Player 2: 6'.
"""
import re
# Match the last string of digits in the passed report
points = re.search(r'\d+$', player_report).group()
return int(points)
# Pass `points` as a "key function".
# The list will be sorted based on the values it returns.
players.sort(key=points, reverse=True)
# Make the sorted list back into a string.
return "\n".join(players)
Supposing that the 'players reports' are in a list:
values = ['Player 1: 3','Player 2: 4','Player 3: 3','Player 4: 5']
values.sort(key=lambda s: [(-int(b),a) for a,b in (s.split(':'),)])
print values
results in
['Player 4: 5', 'Player 2: 4', 'Player 1: 3', 'Player 3: 3']
=============
Bob Loin said he wants to obtain
Player 4: 5, Player 2: 4, Player 1: 3, Player 3: 3
Daniel's Roseman works well or not depending on the treated list.
My solution gives the right result. See the difference on the second list
values = ['Player 1: 3','Player 2: 4','Player 3: 3','Player 4: 5']
print ' ',values
print
print 'Dan',sorted(values, key=lambda s: s.split(': ')[1], reverse=True)
print 'eyq',sorted(values, key=lambda s: [(-int(b),a)
for a,b in (s.split(':'),)])
print '\n===================================\n'
values = ['Player 3: 3','Player 2: 4','Player 1: 3','Player 4: 5']
print ' ',values
print
print 'Dan',sorted(values, key=lambda s: s.split(':')[1], reverse=True)
print 'eyq',sorted(values, key=lambda s: [(-int(b),a)
for a,b in (s.split(': '),)])
result
['Player 1: 3', 'Player 2: 4', 'Player 3: 3', 'Player 4: 5']
Dan ['Player 4: 5', 'Player 2: 4', 'Player 1: 3', 'Player 3: 3']
eyq ['Player 4: 5', 'Player 2: 4', 'Player 1: 3', 'Player 3: 3']
===================================
['Player 3: 3', 'Player 2: 4', 'Player 1: 3', 'Player 4: 5']
Dan ['Player 4: 5', 'Player 2: 4', 'Player 3: 3', 'Player 1: 3']
eyq ['Player 4: 5', 'Player 2: 4', 'Player 1: 3', 'Player 3: 3']
精彩评论