在Python中按元素值对元组进行排序 [英] Sorting tuples by element value in Python
本文介绍了在Python中按元素值对元组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要按特定的tuple元素对Python中的元组列表进行排序,假设它是本例中的第二个元素.我尝试过
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])
我也尝试过
sorted(tupList, key = itemgetter(1))
'''i imported itemgetter, attrgetter, methodcaller from operator'''
,但是两次都返回了相同的列表.我检查了
but the list was returned the same both times. I checked
https://wiki.python.org/moin/HowTo/Sorting
推荐答案
我猜您正在调用 sorted
,但未将结果分配到任何地方.像这样:
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
创建一个新的排序列表,而不是修改原始列表.试试:
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)
或者:
tupList = [(2,16), (4, 42), (3, 23)]
tupList.sort(key = lambda tup: tup[1])
print(tupList)
这篇关于在Python中按元素值对元组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文