【问题标题】:How can i sort for every word in a string for every string in a list?如何为列表中的每个字符串对字符串中的每个单词进行排序?
【发布时间】:2022-01-25 12:25:04
【问题描述】:

对于初学者我是这样做的

text = "Hello I want to make this code better"

x = text.split()

sorted_characters = sorted(x[5])

sortedword = "".join(sorted_characters)

print(sortedword)

我希望代码执行此操作,但我不知道如何分隔单词和列表中的每个字符串:

example=['I like python', 'I like reading books']

输出应该是['I eikl hnopty', 'I eikl adeginp bkoos']

【问题讨论】:

    标签: python python-3.x list function sorting


    【解决方案1】:

    一个班轮: [' '.join([''.join(sorted(z)) for z in i.split()]) for i in example]

    这只是做你所做的,使用python的列表理解功能,并对列表中的每个元素进行排序

    【讨论】:

    • 我怎样才能让它输出 'ouy acn go aefrst ahnt 015', 'adiikklt ckllouuy' 而不是列表和逗号不是字符串?
    • 我不确定我是否理解您的问题,但如果您的意思是如何将其转换为字符串,您可以只使用 ', '.join() 理解列表
    【解决方案2】:

    您可以使用split 将单词从句子中取出并对其进行排序并将它们添加到新字符串中,如下所示...

    text = "Hello I want to make this code better"
    res = ""
    
    for i in text.split():
        temp = ""
    
        for j in sorted(i):
            temp += j
    
        res += f"{temp} "
    
    print(res)
    

    【讨论】:

    • for j in sorted(i): temp += j res += f"{temp}" 你在这里做了什么你能解释一下我还没有学过这些东西 :D 有没有我能做些什么?
    • @PitonGamer - 例如,i += 1i = i + 1 相同。 (这是从 C 继承而来的)。在 Python 中,同样的逻辑可以应用于字符串。它正在向现有字符串添加一个新字符串。
    猜你喜欢
    • 2015-04-15
    • 2015-09-11
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 2014-07-30
    • 2016-05-25
    • 2023-04-07
    相关资源
    最近更新 更多