Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting words in python

Tags:

python

Is it possible in python to sort a list of words not according to the english alphabet but according to a self created alphabet.

like image 712
Preys Avatar asked Jun 14 '10 13:06

Preys


People also ask

Can I sort a string in Python?

In Python, there are two ways, sort() and sorted() , to sort lists ( list ) in ascending or descending order. If you want to sort strings ( str ) or tuples ( tuple ), use sorted() .

How do I sort a list of letters in Python?

Use the Python List sort() method to sort a list in place. The sort() method sorts the string elements in alphabetical order and sorts the numeric elements from smallest to largest. Use the sort(reverse=True) to reverse the default sort order.

What does sort () do in Python?

Python sorted() Function The sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically.


1 Answers

You can normally define custom comparison methods so the sort is performed within your restrictions. I've never coded a line of Python in my life, but it's similar enough to Ruby for me to notice that the following excerpt from this page might help you:

alphabet = "zyxwvutsrqpomnlkjihgfedcba"

inputWords = ["england", "france", "spain", "italy", "greece", "portugal",
              "canada", "usa", "mexico", "peru", "cuba", "chile", "argentina",
              "zimbabwe", "uganda", "congo", "zambia", "namibia", "ghana"]

print sorted(inputWords, key=lambda word: [alphabet.index(c) for c in word])

You might also want to check out these articles. Good luck!

like image 59
Jeriko Avatar answered Oct 13 '22 12:10

Jeriko