1. 程式人生 > 實用技巧 >python習題三

python習題三

題目描述:

對給出的字串進行排序,字串有以下特點,每個詞中都有一位數字(1-9)。將這些詞按照擁有的數字大小進行排序。

注意:如果輸入的是空字串,則輸出空字串。

舉例說明:

  INPUT                OUTPUT
"is2 Thi1s T4est 3a" --> "Thi1s is2 3a T4est"

"4of Fo1r pe6ople g3ood th5e the2" --> "Fo1r the2 g3ood 4of th5e pe6ople"

"" --> ""

靈活的解題方法

def order(sentence):
    return
' '.join(sorted(sentence.split(), key=sorted))

說明:

首先,將字串按空格分隔單個word,使用split()函式;

接著就是按word中的數字進行排序,使用sorted函式,將單個詞進行排序。由於數字一定小於英文字母,所以巧妙地用sorted對key值進行排序。

比如T4est這個word,用sorted排序後是['4', 'T', 'e', 's', 't'],is2排序後是['2', 'i', 's']。首位都是數字,再進行sorted時就會按照數字大小進行排序。