Sorting tuples by element value in Python

前端 未结 1 1414
花落未央
花落未央 2021-01-26 18:34

I need to sort a list of tuples in Python by a specific tuple element, let\'s say it\'s the second element in this case. I tried

sorted(tupList, key = lambda tup         


        
1条回答
  •  北海茫月
    2021-01-26 19:10

    I'm guessing you're calling sorted but not assigning the result anywhere. Something like:

    tupList = [(2,16), (4, 42), (3, 23)]
    sorted(tupList, key = lambda tup: tup[1])
    print(tupList)
    

    sorted creates a new sorted list, rather than modifying the original one. Try:

    tupList = [(2,16), (4, 42), (3, 23)]
    tupList = sorted(tupList, key = lambda tup: tup[1])
    print(tupList)
    

    Or:

    tupList = [(2,16), (4, 42), (3, 23)]
    tupList.sort(key = lambda tup: tup[1])
    print(tupList)
    

    0 讨论(0)
提交回复
热议问题