0

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!

1
  • I'm not really able to visualize what your class structure looks like. Commented Feb 6, 2014 at 17:32

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

I will look it up, but it was how I was sorting the information within my word class
Re: Collections.counter I am actually supposed to compare the hashtable method and a list method for doing this kind of stuff.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.