[Python]如何用两个变量对字符串进行排序?

时间:2011-04-10 18:17:53

标签: python sorting variables

你好我对python有些新意,所以请耐心等待。

我的python程序有以下几行:

打印“玩家1:”+ str(player1points)

打印“玩家2:”+ str(player2points)

打印“玩家3:”+ str(player3points)

打印“玩家4:”+ str(player4points)

玩家#points是我的程序计算出来的,每次运行时都会有所不同。

结果会产生:

球员1:3

球员2:4

球员3:3

球员4:5

如果可能的话,我想对结果进行排序,以便每个玩家的积分首先从最高到最低排名,然后是玩家。如果两个玩家并列积分,那么编号最小的玩家将首先列出。

所以我希望我的结果如下:

球员4:5

球员2:4

球员1:3

球员3:3

任何帮助都将非常感谢!!

5 个答案:

答案 0 :(得分:2)

如果您已经拥有播放器对象或词典,则可以使用以下选项进行排序:

players.sort(key=lambda player: player.score, reverse=True)

如果没有,请处理您的数组并在每个':'

处拆分

样品:

#!/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()

答案 1 :(得分:1)

答案 2 :(得分:0)

sorted(values, key=lambda s: s.split(': ')[1], reverse=True)

答案 3 :(得分:0)

将“key function”传递给list.sort方法可以自定义它的排序方式。

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)

答案 4 :(得分:0)

假设'玩家报告'在列表中:

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

结果

['Player 4: 5', 'Player 2: 4', 'Player 1: 3', 'Player 3: 3']

=============

Bob Loin说他想获得

  

玩家 4 :5,玩家 2 :4,玩家 1 :3,玩家 3 :3

Daniel's Roseman的运作良好与否取决于治疗清单。

我的解决方案给出了正确的结果。请参阅第二个列表中的差异

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(': '),)])

结果

    ['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']