2016-10-24 5 views
0

Ich bin neu bei Python und ich versuche es zu lernen. Ich habe kürzlich versucht zu sortieren, wie das grundlegende Sortieren von Strings. In meinem Code übergebe ich eine Zeichenkette an eine Funktion print_sorted(), diese Zeichenkette wird dann an die Funktion sort_sentence übergeben, die den Satz in Wörter aufteilt und dann mit der Funktion sorted() von python sortiert. Aber aus irgendeinem Grund ignoriert es immer die erste Saite vor dem Sortieren. Kann mir bitte jemand sagen warum? Prost im voraus !!Grundlegende String-Sortierung in Python, mit sortierten()

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

Sind Sie fragen, warum '‚Why'' kommt vor '‘ earth''? Es ist unklar. Aber wenn das so ist, stehen Großbuchstaben vor Kleinbuchstaben; z. B. "W" <"e" 'gibt" True "zurück. –

+1

Es * ist * funktioniert. Welche Ausgabe haben Sie erwartet? –

Antwort

3

Ihre Ausgabe scheint korrekt, da Großbuchstaben vor Kleinbuchstaben stehen.

Wenn Sie Fall ignorieren möchten beim Sortieren Sie str.lower für den key Parameter in sorted(), so etwas wie dies nennen kann:

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

Prost Jungs. Ametuar Fehler, dachte nur nicht an diesen Teil. – Johny

Verwandte Themen