Reputation: 11
Hi for a project at my university i want to get the top n rated elements of which i get from a website.
I managed to get the ratings and the titles of the elements with beautifulsoup. Now i have two lists: one with the titles and one with the ratings. They look like this: Ratings
[4.4, 3.5, 5.0 , 1.5]
Titles
['Title1','Title2','Title3','Title4']
The rankings order is inline with the title order. How can i merge these two lists to get the top n rated elements?
Upvotes: 1
Views: 168
Reputation: 304127
>>> import heapq
>>> A = [4.4, 3.5, 5.0 , 1.5]
>>> B = ['Title1','Title2','Title3','Title4']
>>> heapq.nlargest(2, zip(A, B))
[(5.0, 'Title3'), (4.4, 'Title1')]
Upvotes: 1
Reputation: 767
If you know they are always the same length you could do something like this:
for i in range(0,len(numberList)):
newList.append(titleList[i],numberList[i])
Which would then give you a new list something like:
[('Title1',4.4),('Title2',3.5)]
That you can then sort and use as you please.
Upvotes: 0
Reputation: 113905
>>> ratings = [4.4, 3.5, 5.0 , 1.5]
>>> titles = ['Title1','Title2','Title3','Title4']
>>> sorted(list(enumerate(titles)), key=lambda t:ratings[t[0]])
[(3, 'Title4'), (1, 'Title2'), (0, 'Title1'), (2, 'Title3')]
>>> [t[1] for t in sorted(list(enumerate(titles)), key=lambda t:ratings[t[0]])]
['Title4', 'Title2', 'Title1', 'Title3']
Upvotes: 0
Reputation: 10350
lst1 = [4.4, 3.5, 5.0 , 1.5]
lst2 = ['Title1','Title2','Title3','Title4']
zipped = list(zip(lst1, lst2)) # "merges" the lists
zipped.sort(key=lambda x: x[0], reverse=True) # sorts by ratings, descending
print(zipped)
Output:
[(5.0, 'Title3'), (4.4, 'Title1'), (3.5, 'Title2'), (1.5, 'Title4')]
Now, you can slice the output (zipped
) to your heart's content to get the top however-many titles you want. If, for example, you want the top 2 elements (but only the titles, not the ratings):
n = 2
result = [item[1] for item in zipped[:n]]
print(result)
Output:
['Title3', 'Title1']
Upvotes: 3