Sorting tuples by element value in Python

不问归期 提交于 2020-01-11 14:22:46

问题


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: tup[1])

I have also tried

sorted(tupList, key = itemgetter(1))
'''i imported itemgetter, attrgetter, methodcaller from operator'''

but the list was returned the same both times. I checked

sorting tuples in python with a custom key

sort tuples in lists in python

https://wiki.python.org/moin/HowTo/Sorting


回答1:


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)


来源:https://stackoverflow.com/questions/29656499/sorting-tuples-by-element-value-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!