根据第二个参数对元组进行排序

我有一个看起来像这样的元组列表:


("Person 1",10)

("Person 2",8)

("Person 3",12)

("Person 4",20)

我要生成的是按元组的第二个值按升序排序的列表。因此L [0]应该("Person 2", 8)在排序之后。


我怎样才能做到这一点?使用Python 3.2.2如果有帮助。


富国沪深
浏览 431回答 3
3回答

蛊毒传说

您可以将key参数用于list.sort():my_list.sort(key=lambda x: x[1])或者,更快一点my_list.sort(key=operator.itemgetter(1))(与任何模块一样,您将需要import operator能够使用它。)

千万里不及你

如果您使用的是python 3.x,则可以sorted在mylist上应用该函数。 这只是@Sven Marnach上面给出的答案的补充。# using *sort method*mylist.sort(lambda x: x[1]) # using *sorted function*sorted(mylist, key = lambda x: x[1]) 

心有法竹

 def findMaxSales(listoftuples):        newlist = []        tuple = ()        for item in listoftuples:             movie = item[0]             value = (item[1])             tuple = value, movie             newlist += [tuple]             newlist.sort()             highest = newlist[-1]             result = highest[1]       return result             movieList = [("Finding Dory", 486), ("Captain America: Civil                                   War", 408), ("Deadpool", 363), ("Zootopia", 341), ("Rogue One", 529), ("The  Secret Life of Pets", 368), ("Batman v Superman", 330), ("Sing", 268), ("Suicide Squad", 325), ("The Jungle Book", 364)]             print(findMaxSales(movieList))输出->侠盗一号
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python