开发者

How do I change this particular string into a certain input

I have the following line in my python program

print "Player 1: " +str(player1points)

where 'player1points' is calculate in my program.

The results yield:

Player 1: 3

where the '3' was what the program calculated for that run.

However for one particular function I managed to get help from here

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)

The function will only accept an input:

Player 1: 3

a开发者_StackOverflow社区nd not:

"Player 1: " +str(player1points)

Even though it appears to me that they both yield the same result, how will I be able to to convert

"Player 1: " +str(player1points)

into the appropriate input so the function will accept it.

Examples:

sort_players('Player 1: 3\n'
             '\n'
             'Player 2: 4\n'
             '\n'
             'Player 3: 3\n')

Will give me

Player 2: 4
Player 1: 3
Player 3: 3

Example 2:

sort_payers('Player 1: +str(player1points)\n'
            '\n'
            'Player 2: +str(player2points)\n'
            '\n'
            'Player 3: +str(player3points)\n')

Will give me

AttributeError:'NoneType' object has no attribute 'group'


'Player 1: +str(player1points)\n'

Is just a string, even though it contains something that may be Python code. Thankfully, Python won't magically evaluate that. That string will be passed literally to the function. Look at the syntax highlighting of the line above and compare it to this, which actually adds player1points to the string Player 1::

'Player 1: '+str(player1points)+'\n'

You see, have to put the str call and + outside of the string literal so they mean anything to Python. (And while you're at it, you might want to switch to string formatting, i.e. "Player 1: %d" % player1points or "Player 1: {}".format(player1points).)

The error message specifically is caused by this line:

points = re.search(r'\d+$', player_report).group()

Since there's nothing number-like in the line (only "+str(player1points)"), re.search wil return None instead of a match objects - and None obviously doesn't know anything about groups.


sorted(iterable[, cmp[, key[,reverse]]])

Return a new sorted list from the items in iterable.

Your code is a paddling pool. But it seems that the data you have to treat is a string. So I do:

ch = '''\
Player 1: 3

Player 2: 4

Player 3: 3

Player 4: 5
'''
print ch

import re

pat = re.compile('(Player (\d+): (\d+))')

print '------------'
print '\n'.join(x[2] for x in
                sorted((-int(points),number,report)
                       for (report, number, points)
                       in pat.findall(ch)))

result

Player 1: 3

Player 2: 4

Player 3: 3

Player 4: 5

------------
Player 4: 5
Player 2: 4
Player 1: 3
Player 3: 3

If the input data isn't a string, explain what it is and I will modify the code.


You should generally use formatting strings instead of the + operator for concatenation in python. I'm also not sure why you want to pass a string for which you already have the point value to a function that extracts the point value?

You could try something like this (although I'm not sure why what you have would be failing..)

mystr = "Player 1: %d" % player1points
print points(mystr)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜