我正在尝试解决这个问题:
“你的任务是对给定的字符串进行排序。字符串中的每个单词都将包含一个数字。这个数字就是该单词在结果中应具有的位置。
注意:数字可以是 1 到 9。因此 1 将是第一个单词(而不是 0)。
如果输入字符串为空,则返回空字符串。输入字符串中的单词将仅包含有效的连续数字。
示例:“is2 Thi1s T4est 3a”-->“Thi1s is2 3a T4est”
我尝试首先拆分收到的字符串,然后使用 sort() 函数,但我认为这是按每个单词的大小而不是其中的数字对句子进行排序。
def order(sentence):
words = sentence.split()
words.sort()
return words
print(order("is2 Thi1s T4est 3a"))
Run Code Online (Sandbox Code Playgroud)
它应该对句子进行排序“Thi1s is2 3a T4est”,但我的代码对句子进行排序 ['3a', 'T4est', 'Thi1s', 'is2']
功能版本:
sentence = "is2 Thi1s T4est 3a"
def order(sentence):
# creates a tuple of (int, word) for each word in the sentence
# we need a nested listed comprehension to iterate each letter in the word
# [... for w in sentence.split() ...] -> for each word in the sentence
# [... for l in w ...] -> for each letter in each word
# [... if l.isdigit()] -> if the letter is a digit
# [(int(l), w) ...] -> add a tuple of (int(letter), word) to the final list
words = [(int(l), w) for w in sentence.split() for l in w if l.isdigit()]
words.sort(key=lambda t: t[0])
return " ".join(t[1] for t in words)
print(order(sentence))
>>> Thi1s is2 3a T4est
Run Code Online (Sandbox Code Playgroud)
这里有一个有趣的单线
sentence = "is2 Thi1s T4est 3a"
new = " ".join(t[1] for t in sorted([(int(l), w) for w in sentence.split() for l in w if l.isdigit()], key=lambda t: t[0]))
print(new)
>>> Thi1s is2 3a T4est
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9529 次 |
| 最近记录: |