W tym programie nauczysz się sortować słowa w kolejności alfabetycznej za pomocą pętli for i wyświetlać je.
Aby zrozumieć ten przykład, powinieneś znać następujące tematy programowania w Pythonie:
- Python for Loop
- Ciągi Pythona
- Metody ciągów
W tym przykładzie ilustrujemy, jak słowa mogą być sortowane leksykograficznie (kolejność alfabetyczna).
Kod źródłowy
# Program to sort alphabetically the words form a string provided by the user my_str = "Hello this Is an Example With cased letters" # To take input from the user #my_str = input("Enter a string: ") # breakdown the string into a list of words words = (word.lower() for word in my_str.split()) # sort the list words.sort() # display the sorted words print("The sorted words are:") for word in words: print(word)
Wynik
Posortowane słowa to: przykład z dużymi literami cześć to litery z tym
Uwaga: Aby przetestować program, zmień wartość my_str.
W tym programie przechowujemy ciąg do posortowania w my_str. Za pomocą metody split () ciąg jest konwertowany na listę słów. Metoda split () dzieli ciąg na białe spacje.
Lista słów jest następnie sortowana za pomocą metody sort () i wyświetlane są wszystkie słowa.