首页 > 解决方案 > 对单词使用“排序”函数会给出一个输出,其中字母被拆分和排序

问题描述

我是 python (2.7) 和 stackoverflow 的新手。我正在尝试学习如何使用“排序”功能。当我使用“排序”功能时,句子分成单个字母并按升序对这些字母进行排序。但这不是我想要的。我想按升序对我的单词进行排序。我正在尝试运行此代码

peace = "This is one of the most useful sentences in the whole wide world."

def pinkan (one):
    return sorted (one)

print pinkan (peace)

但我得到的输出是这样的:

[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'T', 'c', 'd', 
'd', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'f', 'f'
, 'h', 'h', 'h', 'h', 'i', 'i', 'i', 'i', 'l', 'l', 'l', 'm', 'n', 'n', 'n', 
'n', 'o', 'o', 'o', 'o', 'o', 'r', 's', 's', 's', 's', 's
', 's', 't', 't', 't', 't', 'u', 'u', 'w', 'w', 'w']

我将不胜感激任何帮助/建议。谢谢 :-)

标签: python-2.7sorting

解决方案


您应该首先使用split()生成单词列表,然后sort()按字母升序对该列表进行排序:

peace = "This is one of the most useful sentences in the whole wide world."
terms = peace.split()
terms.sort(key=str.lower)
output = " ".join(terms)
print(output)

['in', 'is', 'most', 'of', 'one', 'sentences', 'the', 'the', 'This', 'useful',
    'whole', 'wide', 'world.']

推荐阅读