2016-10-24 5 views
0

私はPythonには新しく、私はそれを学ぼうとしています。私は最近、文字列の基本的なソートのような並べ替えを試していました。私のコードでは、関数print_sorted()に文字列を渡しています。この文字列は、文を単語に分割し、pythonのsorted()関数を使用してソートするsort_sentence関数に渡されます。しかし何らかの理由で、ソートする前に常に最初の文字列を無視します。誰かがなぜ私に教えてくれますか?あらかじめ乾杯!ソート済み()を使用して、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

を求めていますか?それは不明だ。しかし、それがそうであれば、大文字は小文字に先行します。例えば ​​"W" <"e" 'は' True'を返します。 –

+1

※*動作しています。あなたはどんな出力を期待していましたか? –

答えて

3

大文字が小文字の前に来るため、出力が正しいようです。あなたはsorted()keyパラメータにstr.lowerを呼び出すことができます並べ替えながら、ケースを無視したい場合は

、このような何か: `earth'`「Why'`は`の前に来る」なぜあなたは

>>> 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

関連する問題