Combine two lists and then sort each column

前端 未结 1 790
孤独总比滥情好
孤独总比滥情好 2021-01-25 21:58

I have a file [ Name Age Marks] . I have stored each values of Name in a list1 . Marks in list2. I have combined both lists using zip function in python:

 list3         


        
相关标签:
1条回答
  • 2021-01-25 22:47

    sorted, list.sort accept optional key function. Return values of the function are used for comparison.

    >>> list3 = [('Steve',32),('David',65),('Ram',43),('Mary',87)]
    >>> sorted(list3, key=lambda item: item[1])
    [('Steve', 32), ('Ram', 43), ('David', 65), ('Mary', 87)]
    
    >>> sorted(list3, key=lambda item: -item[1]) # negate the return value.
    [('Mary', 87), ('David', 65), ('Ram', 43), ('Steve', 32)]
    
    >>> sorted(list3, key=lambda item: item[1], reverse=True) # using `reverse`
    [('Mary', 87), ('David', 65), ('Ram', 43), ('Steve', 32)]
    
    0 讨论(0)
提交回复
热议问题