2016-10-24 65 views
0

我是新來的python,我試圖去了解它。我最近正在嘗試排序,就像字符串的基本排序。在我的代碼中,我將字符串傳遞給函數print_sorted(),然後將該字符串傳遞給sort_sentence函數,該函數將句子分解爲單詞,然後使用python的sorted()函數對其進行排序。但由於某種原因,它總是在排序前忽略第一個字符串。有人可以告訴我爲什麼嗎?提前歡呼!在python中使用排序的基本字符串排序()

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'] 
+2

你問爲什麼'「Why''到來之前'」 earth''?目前尚不清楚。但是,如果是這樣,大寫字母在小寫字母前面;例如'「W」<「e」'返回「真」。 –

+1

它*工作*。你期望什麼產出? –

回答

3

您的輸出看起來正確,因爲大寫字母出現在小寫字母之前。

如果你想忽略大小寫排序時,你可以在sorted()調用str.lowerkey參數,像這樣:

>>> 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'] 
+0

乾杯傢伙。 ametuar錯誤,只是沒有想到那一部分。 – Johny