【问题标题】:How to sort a Tuple using two parameters?如何使用两个参数对元组进行排序?
【发布时间】:2021-12-24 05:18:00
【问题描述】:

元组列表包含[('John',32),('Jane',22),('Doe',32),('Mario',55)]。我想按年龄对列表进行排序,按字母顺序按姓名对相同年龄的人进行排序?到目前为止,我只在 sorted() 函数中使用了 Lambda 函数,键为 name 或 age ?

输出应该是 -> [('Jane',22),('Doe',32),('John',32),('Mario',55)]

【问题讨论】:

  • key=lambda tup: (tup[1], tup[0])

标签: python python-3.x list sorting tuples


【解决方案1】:

给定:

>>> lot=[('John',32),('Jane',22),('Doe',32),('Mario',55)]

你可以组成一个新的元组:

>>> sorted(lot, key=lambda t: (t[1],t[0]))
[('Jane', 22), ('Doe', 32), ('John', 32), ('Mario', 55)]

或者,在这种情况下,您可以反转元组:

>>> sorted(lot, key=lambda t: t[::-1])
[('Jane', 22), ('Doe', 32), ('John', 32), ('Mario', 55)]

您还可以将itemgetter 与两个参数一起使用,按照您希望结果键元组的顺序:

>>> from operator import itemgetter
>>> sorted(lot, key=itemgetter(1,0))
[('Jane', 22), ('Doe', 32), ('John', 32), ('Mario', 55)]

【讨论】:

  • 谢谢。我还发现,在里面的第一个解决方案中,我们可以使用“ - ”进行反转。 key=lambda t:(t[1],-t[0])
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 2014-08-05
  • 2014-07-22
  • 2011-07-15
  • 2016-07-26
相关资源
最近更新 更多