Introduction
Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result.
Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).
If the input string is empty, return an empty string. The words in the input String will only contain valid consecutive numbers.
Examples
“is2 Thi1s T4est 3a” --> “Thi1s is2 3a T4est”
“4of Fo1r pe6ople g3ood th5e the2” --> “Fo1r the2 g3ood 4of th5e pe6ople”
“” --> “”
Solution
#返回每个单词中所包含的数字
#word中不包含数字的时候,返回None
def extract_number(word):
for l in word:
if l.isdigit(): return int(l)
return None
#将sentence分割为字符串序列,再按所包含数字升序排列,最后用空格连接
def order(sentence):
return ' '.join(sorted(sentence.split(), key=extract_number))
solution
def order(s):
z = []
for i in range(1,10):
for j in s.split():
if str(i) in j:
z.append(j)
return " ".join(z)
solution
def order(sentence):
def sort_key(s):
return next(c for c in s if c.isdigit())
return ' '.join(sorted(sentence.split(), key=sort_key))
solution
def order(sentence):
return " ".join(sorted(sentence.split(), key=lambda x: int(filter(str.isdigit, x))))
solution
def order(words):
return ' '.join(sorted(words.split(), key=lambda w:sorted(w)))