I want to sort a nested list by the numerical values in the second entry of the nested lsits.
name= ['Harry', 'Berry', 'Tina', 'Akriti', 'Harsh']
score = [37.21, 37.21, 37.2, 41.0, 39.0]
mylist = [[title, grade] for title in name for grade in score]
test = sorted(mylist, key=lambda x:x[1])
But this duplicates entries for some reason. Why doesn't it just sort the list by the second entries in the nested lists?
test
[['Harry', 37.2], ['Berry', 37.2], ['Tina', 37.2], ['Akriti', 37.2], ['Harsh', 37.2], `['Harry', 37.21], ['Harry', 37.21], ['Berry', 37.21], ['Berry', 37.21], ['Tina', 37.21], ['Tina', 37.21], ['Akriti', 37.21], ['Akriti', 37.21], ['Harsh', 37.21], ['Harsh', 37.21], ['Harry', 39.0], ['Berry', 39.0], ['Tina', 39.0], ['Akriti', 39.0], ['Harsh', 39.0], ['Harry', 41.0], ['Berry', 41.0], ['Tina', 41.0], ['Akriti', 41.0], ['Harsh', 41.0]]`
CodePudding user response:
You want zip
:
>>> name= ['Harry', 'Berry', 'Tina', 'Akriti', 'Harsh']
>>> score = [37.21, 37.21, 37.2, 41.0, 39.0]
>>> sorted(zip(score, name))
[(37.2, 'Tina'), (37.21, 'Berry'), (37.21, 'Harry'), (39.0, 'Harsh'), (41.0, 'Akriti')]
Think of zip
as adding the two lists together:
[(score[0], name[0]), (score[1], name[1]), ...]
whereas the nested comprehension you were doing is more like multiplying them:
[[name[0], score[0]], [name[1], score[0]], [name[2], score[0], ..., [name[0], score[1]], [name[1], score[1]], [name[2], score[1], ...]
CodePudding user response:
Your iterating twice.
# using enumerate
mylist = [[title, score[ind]] for ind, title in eunmerate(name)]
# Using zip
mylist = zip(name, score)