Python 如何按数值对字符串中的单词进行排序

Python 如何按数值对字符串中的单词进行排序,python,Python,我正在努力解决这个问题: “您的任务是对给定字符串进行排序。字符串中的每个单词都将包含一个数字。该数字是该单词在结果中的位置 注意:数字可以是1到9。因此1将是第一个字(不是0) 如果输入字符串为空,则返回空字符串。输入字符串中的单词将仅包含有效的连续数字 示例:“is2 Thi1s T4est 3a”->“Thi1s is2 3a T4est” 我尝试先拆分收到的字符串,然后使用sort()函数,但我认为这是根据每个单词的大小而不是单词中的数字对句子进行排序 def顺序(句子): 单词=句子

我正在努力解决这个问题:

“您的任务是对给定字符串进行排序。字符串中的每个单词都将包含一个数字。该数字是该单词在结果中的位置

注意:数字可以是1到9。因此1将是第一个字(不是0)

如果输入字符串为空,则返回空字符串。输入字符串中的单词将仅包含有效的连续数字

示例:“is2 Thi1s T4est 3a”->“Thi1s is2 3a T4est”

我尝试先拆分收到的字符串,然后使用sort()函数,但我认为这是根据每个单词的大小而不是单词中的数字对句子进行排序

def顺序(句子):
单词=句子
words.sort()
回话
打印(订单(“is2 Thi1s T4est 3a”))

它应该像这样排列句子“Thi1s is 2 3a T4est”,但我的代码像这样排列句子['3a',T4est',Thi1s',is 2']

这并不漂亮,但你可以将句子中的每个单词分割成字符

def顺序(句子):
指数=[]
单词=[]
用于句子中的单词。拆分():
字母=[单词中字母对字母]
对于字母中的字母:
尝试:
指数+=[整数(字母)-1]
除:
通过
输出=[]
对于索引中的索引:
输出+=[句子.拆分()[索引]]
返回输出
如果希望输出为字符串,可以更改return语句:

return”“。连接(输出)

这将起作用,逐行评论流程:

def顺序(句子):
单词=句子
###从字符串中提取数字(单个单词)
nums=[int(''.join(filter(str.isdigit,x)))表示x的单词]
###把数字和单词配对
dictionary=dict(zip(nums,words))
###根据提取的数字进行排序
sorted_x=sorted(dictionary.items(),key=lambda kv:kv[0])
###只取单词(不取数字)
结果=[x[1]表示排序的x中的x]
返回结果
打印(订单(“is2 Thi1s T4est 3a”))
###输出:
['Thi1s','is2','3a','T4est']

我不打算发布答案,因为这听起来像是家庭作业

也就是说,还有其他答案不那么清晰/易读。为了可读性,我在本例中排除了列表扩展

def order(sentence):
    words = sentence.split()
    ordered_words = sorted(words, key=int_from_word)
    return " ".join(ordered_words)

def int_from_word(word):
    for character in word:
        if character.isdigit():
            return int(character)
    return None

print(order("is2 Thi1s T4est 3a"))
输出:

Thi1s is2 3a T4est
功能版本:

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
这是一条有趣的单行线

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
使用regex和
sort()
,因为还没有人这样做:

import re

s = "is2 Thi1s T4est 3a"
words = s.split()

myre = re.compile(r'\d+')
words.sort(key=lambda x: myre.findall(x))

print(' '.join(words))
由于OP有一个单行程序(效率较低,可读性较差):


我相信这是一个家庭作业的问题,所以我张贴了最简单的方法,我可以解决它

def find_number(word): #returns the number present in the string
    for i in range(len(word)):
        if(word[i].isdigit()):
            num=""
            while(i<len(word) and word[i].isdigit()):
                num+=word[i]
                i+=1
            return int(num)
def order(sentence):
    od={}
    ct="a"
    for i in sentence.split():
        #numbering the strings so that if there are duplicates they are not lost
        od[ct+i]=find_number(i)
        ct=chr(ord(ct)+1)
    for i in sorted(od.values()):
        for j in od: #we can use other way of printing but this is the simplest but way less efficient
            if (od[j]==i):
                print(j[1:])
                break
s=input()
order(s)
def find_number(word):#返回字符串中的数字
对于范围内的i(len(word)):
if(word[i].isdigit()):
num=“”

while(iYep),您的代码是按照单词的词典(“词典”)对单词进行排序的排序。您需要一个键函数,可以找到每个单词中的数字,并使用它。因为这很可能是家庭作业,您可能无法获得完整的解决方案。您应该从上面的注释这样的正确方向开始。正如AKX提到的,您需要向sorted的
key
参数传递一些内容,并且需要做一个只能从每个单词中提取数字的函数。一旦你做到了这一点,答案就是
排序(words,key=get\u number\u from\u word)
。尝试创建
get\u number\u from\u word
函数。例如
get\u number\u from\u word(“T4est”)
应该返回
“4“
4
。这是最清楚的解决方案。@JimWright您应该添加一个
”.join
to
order
以获得完整性哪部分@RaúlSantamaría?我将向answer@Raúlsantamariía不要被一行文字所诱惑。它会降低可读性,这一点非常重要。整个事情,尤其是这个[(int(l),w)表示句子中的w。如果l.isdigit(),split()表示句子中的l]@劳尔桑塔马利亚添加了一些注释,解释了thatDan的不同部分,他说,在实际代码中不应该使用一行程序,但探索更高级的python语法是有帮助的。
def find_number(word): #returns the number present in the string
    for i in range(len(word)):
        if(word[i].isdigit()):
            num=""
            while(i<len(word) and word[i].isdigit()):
                num+=word[i]
                i+=1
            return int(num)
def order(sentence):
    od={}
    ct="a"
    for i in sentence.split():
        #numbering the strings so that if there are duplicates they are not lost
        od[ct+i]=find_number(i)
        ct=chr(ord(ct)+1)
    for i in sorted(od.values()):
        for j in od: #we can use other way of printing but this is the simplest but way less efficient
            if (od[j]==i):
                print(j[1:])
                break
s=input()
order(s)