0

I have a nested list having elements of format ['name',float_val].

Nlist = [['naveen',31.5],['murali',44.1],['sai',23.1],['satya',23.1]]

I want to sort the above nested list by float object. How should I specify the 'key' argument in sort() function to fulfill my need?

martineau
  • 112,593
  • 23
  • 157
  • 280

2 Answers2

0

Use this

sort(x, key=lambda x: x[1])
Pablo Martinez
  • 431
  • 2
  • 6
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/22416923) – Michał Ziober Mar 09 '19 at 14:08
  • @MichałZiober an answer being code-only [DOES NOT warrant deletion](https://meta.stackoverflow.com/q/256359/6296561). If you feel like it, downvote it, but deleting code-only is overkill in most cases (including this one). – Zoe stands with Ukraine Mar 09 '19 at 15:40
0

According the original Python documentation:

Both list.sort() and sorted() have a key parameter to specify a function to be called on each list element prior to making comparisons.

Note that you can use both list.sort() or sorted():

Python lists have a built-in list.sort() method that modifies the list in-place. There is also a sorted() built-in function that builds a new sorted list from an iterable.

You can find some useful examples here.

# take second element for sort
def takeSecond(elem):
    return elem[1]

# your list
Nlist = [['naveen',31.5],['murali',44.1],['sai',23.1],['satya',23.1]]

# sort list with key
Nlist.sort(key=takeSecond)

# print list
print('Sorted list:', Nlist)

Out:

Sorted list: [['sai', 23.1], ['satya', 23.1], ['naveen', 31.5], ['murali', 44.1]]
Geeocode
  • 5,347
  • 2
  • 19
  • 33