首页 > 解决方案 > 排序方法的Python字母顺序显示错误的顺序

问题描述

我刚刚学习 python,我遇到了一个按字母顺序排序单词的代码。

我的代码是:

my_str="Welcome to Python"
words = my_str.split()
words.sort()
print("The sorted words are:")
for word in words:
    print(word)

我的结果是:

排序后的单词是:

Python

Welcome

to

我的意思是它按字母顺序排序,然后它应该结果为

Python

to

Welcome

我很困惑,无法在学习过程中继续前进,你的见解会很有帮助。

标签: pythonpython-3.x

解决方案


你可以试试:

my_str="Welcome to Python"
some_list = my_str.split()
some_list.sort(key=str.casefold)

print("The sorted words are:")
for word in some_list:
    print(word)

输出将是:

Python
to
Welcome

推荐阅读