要求:给定一个句子,句子中的每个单词都包含一个数字,要求根据该数字大小对原句子重新排序。
测试用例如下:
"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(""))
本文介绍了一种使用Python对特殊格式句子进行排序的方法。这种句子中每个单词都包含一个数字,算法会依据这些数字对单词进行重新排序。通过正则表达式提取数字并作为排序关键字,实现了对句子的快速准确排序。
1464

被折叠的 条评论
为什么被折叠?



