算法题:按字符串中的数字大小排序,python实现
程序员文章站
2024-02-23 19:31:58
...
要求:给定一个句子,句子中的每个单词都包含一个数字,要求根据该数字大小对原句子重新排序。
测试用例如下:
"pyt3hon h1as s5ome po7wer functi9ons" --> "h1as pyt3hon s5ome po7wer functi9ons"
"pytho1n i6s pow2erful" --> "pytho1n pow2erful i6s"
"" --> ""
python 一行代码实现,解决问题的关键思路是提取出每个单词的数字
import re
def sortSentence(sentence):
if sentence is "":
return sentence
return ' '.join(sorted(sentence.split(), key=lambda x:re.findall(r"\d+\.?\d*", x)))
if __name__ == '__main__':
sentence1 = "pyt3hon h1as s5ome po7wer functi9ons"
sentence2 = "pytho1n i6s pow2erful"
print(sortSentence(sentence1))
print(sortSentence(sentence2))
print(sortSentence(""))
下一篇: grep -v 的使用