1

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?

4 Answers 4

3
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']
Sign up to request clarification or add additional context in comments.

Comments

1
>>> 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')]

Comments

0
>>> 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']

2 Comments

+1 for answering OP's question exactly, though I think zip and a list comp to get the title may be a little clearer!
@adsmith: I agree. I saw the zip solution, and posted this, just to offer another way of doing it
0

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.

1 Comment

It'd be better to use a list comprehension here.

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.