如何排序数字列表忽略除数字以外的所有字符

时间:2016-02-22 00:58:11

标签: python list python-2.7 sorting

如何对忽略特殊字符的数字列表进行排序。 例如:

[45, 10, 15, 30, "18*"]其中“18 *”是一个字符串,其余为整数

我希望它像这样排序:

[10, 15, "18*", 30, 45]

这是我的整个代码,如果你需要它 - 它是一个数字猜谜游戏跟踪你在列表中的猜测,并用星号标记正确的猜测:

# 1. Generate random integer

import random 
randomNumber = random.randint( 1, 100 )

# 2. Take user input
guessList = []

userGuess = int( raw_input( "Guess an integer between 1 and 100\n> " ))
guessList.append(userGuess)

if userGuess == randomNumber:
    print( "Wow! First try!" )

# 4. High/low loop that terminates if user types "113" or guesses number



while userGuess != randomNumber and userGuess != 113:

    if userGuess > randomNumber:
        userGuess = int( raw_input( 'Your guess is too high! Guess another integer or type "113" to quit.\n> ' ))
        if userGuess != randomNumber:
            guessList.append(str(userGuess))

    if userGuess < randomNumber:
        userGuess = int( raw_input( 'Your guess is too low! Guess another integer or type "113" to quit.\n> ' ))
        if userGuess != randomNumber:
            guessList.append(str(userGuess))


# 5. Endgame outputs depending on if they user quit or guessed the number

if userGuess == 113:
    print ( "You have quit the game. Better luck next time." )

if userGuess == randomNumber:
    guessList.append( str(userGuess) + "*" )
    print ( " You guessed the number! You are a magician! Your guesses were: " )
    print ( guessList )

请告诉我需要使用的排序算法。

1 个答案:

答案 0 :(得分:0)

首先,定义一个将str转换为int的函数:

def transform(item):
    """If item is int, return it unchanged. Otherwise it should be a string of
    one or more digits followed by '*'; strip '*' and return the digits as int.
    """
    return item if isinstance(item, int) else int(item.strip('*'))

然后将函数the key argument传递给内置sorted

>>> ls = [45, 10, 15, 30, "18*"]
>>> sorted(ls, key=transform)
[10, 15, "18*", 30, 45]
>>> # list.sort also accepts a `key` argument
>>> ls.sort(key=transform)
>>> ls
[10, 15, "18*", 30, 45]