Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort two lists in python?

I am counting some occurrences of words in a text, and I have two lists : the first contains the words, the second contains the occurrences.

So at the end of the analysis I have something like

listWords : ["go", "make", "do", "some", "lot"]
listOccurrences: [2, 4, 8, 1, 5]

And I want to sort those two lists following listOccurrences DESC, so I would have :

listWords : ["do", "lot", "make", "go", "some"]
listOccurrences: [8, 5, 4, 2, 1]

Is there any way I can do this ? Or do you know any other way more "natural" than two lists ? (Like a single "list" where every occurrence is referenced by a word)

like image 537
Malik Avatar asked Dec 04 '25 17:12

Malik


2 Answers

>>> listWords = ["go", "make", "do", "some", "lot"]
>>> listOccurrences = [2, 4, 8, 1, 5]
>>> listTmp = zip(listOccurrences, listWords)
>>> listTmp
[(2, 'go'), (4, 'make'), (8, 'do'), (1, 'some'), (5, 'lot')]
>>> listTmp.sort(reverse=True)
>>> listTmp
[(8, 'do'), (5, 'lot'), (4, 'make'), (2, 'go'), (1, 'some')]
>>> zip(*listTmp)
[(8, 5, 4, 2, 1), ('do', 'lot', 'make', 'go', 'some')]
>>> listOccurrences, listWord = zip(*listTmp)

Note that the obvious data type for a key:values pairs (here : word:count) is a dict. FWIW you may want to have a look at collections.Counter.

Edit : For the sake of completeness: you can also use the builtin sorted() function instead of list.sort() if you want to cram all this in a single line statement (which might not be such a good idea wrt/ readability but that's another story):

>>> listWords = ["go", "make", "do", "some", "lot"]
>>> listOccurrences = [2, 4, 8, 1, 5]
>>> listOccurrences, listWords = zip(*sorted(zip(listOccurrences, listWords), reverse=True))
>>> listWords
('do', 'lot', 'make', 'go', 'some')
>>> listOccurrences
(8, 5, 4, 2, 1)
like image 52
bruno desthuilliers Avatar answered Dec 06 '25 08:12

bruno desthuilliers


Another way of doing this to have your data in a dictionary. As you are counting occurrence of word therefore listwords will have unique words and use can use it as dictionary key. You can use python sorted method to sort the keys and values in same order.

listWords = ["go", "make", "do", "some", "lot"]

listOccurrences = [2, 4, 8, 1, 5]

dict = {}

i=0

while(len(listWords) > i):

    dict[listWords[i]] = listOccurrences[i];

    i = i + 1


print sorted(dict, key=dict.get, reverse=True)

print sorted(dict.values(), reverse=True)
like image 42
Pankaj Avatar answered Dec 06 '25 06:12

Pankaj