如何按数字值对字符串的单词排序

时间:2019-07-10 16:12:28

标签: python

我正在尝试解决此问题:

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

注意:数字可以是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"))

它应该对这样的句子进行排序:“ Thi1s is2 3a T4est”,但是我的代码对句子进行排序[[3a”,“ T4est”,“ Thi1s”,“ is2”]

6 个答案:

答案 0 :(得分:2)

我不想发布答案,因为这听起来像是作业。

也就是说,还有其他一些答案不太清晰/可读。为了便于阅读,我将列表扩展放在此示例之外。

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

答案 1 :(得分:1)

功能版本:

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

答案 2 :(得分:0)

这不是很漂亮,但是您可以将句子中的每个单词分解为字符。

def order(sentence):
    indices=[]
    words=[]
    for word in sentence.split():
        letters=[letter for letter in word]
        for letter in letters:
            try:
                indices+=[int(letter)-1]
            except:
                pass
    output=[]
    for index in indices:
        output+=[sentence.split()[index]]
    return output

如果您希望输出为字符串,则可以更改return语句:

return " ".join(output)

希望这会有所帮助!

答案 3 :(得分:0)

这将起作用,逐行注释该过程:

def order(sentence):
    words = sentence.split()
    ### extract the number from the string (single word)
    nums = [ int(''.join(filter(str.isdigit, x))) for x in words ]
    ### pair the number to the word
    dictionary = dict(zip(nums, words))
    ### sort based on the number extracted
    sorted_x = sorted(dictionary.items(), key=lambda kv: kv[0])
    ### take only word (and not number coupled)
    result = [ x[1] for x in sorted_x ]
    return result

print(order("is2 Thi1s T4est 3a"))
### output:
['Thi1s', 'is2', '3a', 'T4est']

答案 4 :(得分:0)

使用正则表达式和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只能放置一个衬纸(效率较低且可读性较差):

import re

s = "is2 Thi1s T4est 3a"
new = ' '.join(sorted(s.split(), key=lambda x: re.findall(r'\d+', x)))
print(new)

答案 5 :(得分:0)

这是我的第一个答案。

我相信这是一个家庭作业问题,所以我发布了解决问题的最简单方法。

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)