一道简单的字符串题,需要根据字符串内每个单词内数字的大小将字符排序,比如:
"is2 Thi1s T4est 3a" --> "Thi1s is2 3a T4est"
"4of Fo1r pe6ople g3ood th5e the2" --> "Fo1r the2 g3ood 4of th5e pe6ople"
https://www.codewars.com/kata/55c45be3b2079eccff00010f
思路:
先把字符串输入text转成list,这样可以方便地通过下标访问每个单词。
然后遍历list,找到每个单词里的数字,再通过新建字典里的键值对{数字:单词下标},记录当前单词的下标,同时建一个list存数字。
将list 排序,然后顺序扫描list 内元素,利用刚才的键值对得到单词下标,通过下标访问单词并将其复制到res中。
最后给res里的单词排好格式并输出。
def order(sentence):
dict = {}
list = []
sentence_split = sentence.split(" ")
for item in sentence_split:
for char in item:
a_code = ord(char)
if a_code >= ord("0") and a_code <= ord("9"):
dict[char] = sentence_split.index(item)
list.append(a_code - ord("0"))
break
list.sort()
res = []
for i in list:
res.append(sentence_split[dict[str(i)]])
return " ".join(item for item in res)