为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

富国沪深 2019-12-21 11:01:50
我有一个看起来像这样的元组列表:("Person 1",10)("Person 2",8)("Person 3",12)("Person 4",20)我要生成的是按元组的第二个值按升序排序的列表。因此L [0]应该("Person 2", 8)在排序之后。我怎样才能做到这一点?使用Python 3.2.2如果有帮助。
查看完整描述

3 回答

?
蛊毒传说

TA贡献1895条经验 获得超3个赞

您可以将key参数用于list.sort():


my_list.sort(key=lambda x: x[1])

或者,更快一点


my_list.sort(key=operator.itemgetter(1))

(与任何模块一样,您将需要import operator能够使用它。)


查看完整回答
反对 回复 2019-12-21
?
千万里不及你

TA贡献1784条经验 获得超9个赞

如果您使用的是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]) 


查看完整回答
反对 回复 2019-12-21
?
心有法竹

TA贡献1866条经验 获得超5个赞

 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))

输出->侠盗一号


查看完整回答
反对 回复 2019-12-21
  • 3 回答
  • 0 关注
  • 428 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信