python中的基本字符串排序,使用sorted()
我是python新手,我正在努力学习它。我最近尝试了排序,比如字符串的基本排序。在我的代码中,我将一个字符串传递给函数print_sorted(),然后该字符串将传递给sort_语句函数,该函数将语句分解为单词,然后使用python的sorted()函数对其进行排序。但由于某些原因,它总是在排序之前忽略第一个字符串。有人能告诉我为什么吗?提前干杯python中的基本字符串排序,使用sorted(),python,sorting,Python,Sorting,我是python新手,我正在努力学习它。我最近尝试了排序,比如字符串的基本排序。在我的代码中,我将一个字符串传递给函数print_sorted(),然后该字符串将传递给sort_语句函数,该函数将语句分解为单词,然后使用python的sorted()函数对其进行排序。但由于某些原因,它总是在排序之前忽略第一个字符串。有人能告诉我为什么吗?提前干杯 def break_words(stuff): words = stuff.split( ) return words def so
def break_words(stuff):
words = stuff.split( )
return words
def sort_words(words):
t = sorted(words)
return t
def sort_sentence(sentence):
words = break_words(sentence)
return sort_words(words)
def print_sorted(sentence):
words = sort_sentence(sentence)
print words
print_sorted("Why on earth is the sorting not working properly")
Returns this ---> ['Why', 'earth', 'is', 'not', 'on', 'properly', 'sorting', 'the', 'working']
您的输出似乎正确,因为大写字母在小写字母之前 如果要在排序时忽略大小写,可以调用
sorted()
中的键
参数的str.lower
,如下所示:
>>> sorted("Why on earth is the sorting not working properly".split())
['Why', 'earth', 'is', 'not', 'on', 'properly', 'sorting', 'the', 'working']
>>> sorted("Why on earth is the sorting not working properly".split(), key=str.lower)
['earth', 'is', 'not', 'on', 'properly', 'sorting', 'the', 'Why', 'working']
您的输出似乎正确,因为大写字母在小写字母之前 如果要在排序时忽略大小写,可以调用
sorted()
中的键
参数的str.lower
,如下所示:
>>> sorted("Why on earth is the sorting not working properly".split())
['Why', 'earth', 'is', 'not', 'on', 'properly', 'sorting', 'the', 'working']
>>> sorted("Why on earth is the sorting not working properly".split(), key=str.lower)
['earth', 'is', 'not', 'on', 'properly', 'sorting', 'the', 'Why', 'working']
你是在问为什么
'why'
出现在'earth'
之前吗?不清楚。但如果是这样,大写字母优先于小写字母;e、 例如,“W”<“e”
返回True
。它正在工作。您希望得到什么样的输出?您是否在问为什么'why'
出现在'earth'
之前?不清楚。但如果是这样,大写字母优先于小写字母;e、 例如,“W”<“e”
返回True
。它正在工作。你们期望的产量是多少?干杯,伙计们。一个错误,只是没想到那一部分。干杯,伙计们。一个错误,只是没有想到那一部分。