简体   繁体   中英

Sorting Words Into the Alphabetic Order in Python

I am trying to write a python code that can sort lowercase words in the order of the dictionary. Firstly sort the words by the first letter, if the first letter is the same, then compare the second letter, and so on. After sorting, print out the words in the sorted order, separated by commas. The inputed words needs to be seperated with commas aswell.Thanks in advance.

I think there is part of this question is already answered here . but I'll post the code that should answer your question completely.

def quicksort(lst):
    if not lst:
        return []
    return (quicksort([x for x in lst[1:] if x <  lst[0]])
            + [lst[0]] +
            quicksort([x for x in lst[1:] if x >= lst[0]]))

s = "I am trying to write a python code that can sort lowercase words in the order of the dictionary"
s = s.lower().split()
print(s)
arr = s
print("Sorted array is:", quicksort(arr))

If your dictionnary is actually a Python list containning words we can sort it directly. If it is a Python dictionnary a direct sort will sort by the keys and we need to use a lambda function to sort by the values.

words = ['yes','no','black','white']
print("# unsorted list")
print(words)
words.sort()
print("# sorted list")
print(words)
print('')

frenchWords={'yes':'oui','no':'non','black':'noire','white':'blanc'}
print("# unsorted dictionnary")
print(frenchWords)

print("# default dictionnary sort")
for i in sorted (frenchWords):
  print((i, frenchWords[i]))
  
print("# dictionnary keys sorted")
for i in sorted (frenchWords.keys()):
  print(i)

print("# dictionnary sorted by values")  
print(sorted(frenchWords.items(), key = lambda kv:(kv[1], kv[0])))

output

# unsorted list
['yes', 'no', 'black', 'white']
# sorted list
['black', 'no', 'white', 'yes']
# unsorted dictionnary
{'yes': 'oui', 'no': 'non', 'black': 'noire', 'white': 'blanc'}
# default dictionnary sort
('black', 'noire')
('no', 'non')
('white', 'blanc')
('yes', 'oui')
# dictionnary keys sorted 
black
no
white
yes
# dictionnary sorted by values
[('white', 'blanc'), ('black', 'noire'), ('no', 'non'), ('yes', 'oui')]

Maybe try converting to ASCII using ord(), and then perform a stable sort such as radix sort

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM