Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python sort one list from another list [duplicate]

I have been working on this program for a while and can't figure out how to sort one of my lists from the contents in the second list. For this program, I have a list of words and I also have a list of how many times the word is in the file I opened. I need to sort the word list according to the frequency of the word in descending order. I have to write a separate function to do this according to the assignment. I have a function that was given to the class to use but it only sorts one list. Here is the function I have and need to modify:

def selectionsort(mylist):
    for i in range(len(mylist)):
       max_i = i
       for j in range( i + 1, len(mylist) ):
           if mylist[j] > mylist[max_i]:
                max_i = j
       temp = mylist[max_i]
       mylist[max_i] = mylist[i]
       mylist[i] = temp

I currently have two lists that look like this:

mylist = ["the", "cat", "hat", "frog"]
frequency = [4, 1, 2 ,1]       

4 is the frequency of "the", 1 is the frequency of "cat" and so on.

My goal is to have mylist sorted like this:

 mylist = ["the", "hat", "cat", "frog"]

How should i modify the function i have so it sorts mylist using the corresponding values from the frequency list?

I am using Python 3.3

like image 228
user3088605 Avatar asked Mar 16 '26 17:03

user3088605


1 Answers

Here you go! Using sorted and zip:

sortedlist = [i[0] for i in sorted(zip(mylist, frequency), key=lambda l: l[1], reverse=True)]

Here's a little demo:

>>> mylist
['the', 'cat', 'hat', 'frog']
>>> frequency = [4, 1, 3, 2]
>>> sortedlist = [i[0] for i in sorted(zip(mylist, frequency), key=lambda l: l[1], reverse=True)]
>>> sortedlist
['the', 'hat', 'frog', 'cat']

Hope this helps!

like image 101
aIKid Avatar answered Mar 18 '26 06:03

aIKid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!