Grogie
Grogie

Reputation: 7

Python 3.3: Sorting a List of Objects/Methods

I apologize I am not sure of the terminology of Python.

I have a Class called "Word" and what it does is count and store all the words in a given text file as a tuple I.e.

self.listName = [('world', 2), ('hello', 3), ('stack', 1), ('overflow', 2)] 

where the item of index 0 is the word and index 1 is the occurrences. This is stored within the the class "word". is there any way I can use the

listName.sort() 

or

sorted(listName, key=lambda Word: Word[0])

to give me the following list:

self.listName = [('hello', 3), ('overflow', 2), ('stack', 1), ('world', 2)] 

I want to try to use this rather than attempting to create a new sorting function (which I believe I can do, but I have not been successful)?

I think I should also mention that the List and the Word classes are in different classes (if that makes a difference).

thanks in advance!

Upvotes: 0

Views: 437

Answers (3)

Grogie
Grogie

Reputation: 7

I actually got it to work, I needed a "over rider method" (? - where I need to define __lt__ to compare the str element of Word()) though because I got this error: TypeError: unorderable types: str() < Word()

Upvotes: 0

blakejgriffin
blakejgriffin

Reputation: 26

To sort your list,

listname.sort(key=lambda x:x[0])

should sort the list in place alphabetically by word.

Also, you may want to look up

collections.counter

as it serves a similar purpose to what you are doing

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239573

You don't need to specify the key at all,

listName = [('world', 2), ('hello', 3), ('stack', 1), ('overflow', 2)]
print(sorted(listName))

Output

[('hello', 3), ('overflow', 2), ('stack', 1), ('world', 2)]

For more information about how this comparison is done, please check this documentation page Comparing Sequences and Other Types

Upvotes: 2

Related Questions