【问题标题】:Sorting tuples by element value in Python在 Python 中按元素值对元组进行排序
【发布时间】:2015-06-21 18:49:13
【问题描述】:

我需要按特定元组元素对 Python 中的元组列表进行排序,假设它是本例中的第二个元素。我试过了

sorted(tupList, key = lambda tup: tup[1])

我也试过

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

但是两次返回的列表都是一样的。我检查了

sorting tuples in python with a custom key

sort tuples in lists in python

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

【问题讨论】:

  • 提醒:在列表上调用sorted 不会修改原始列表。如果你正在做sorted(seq); print(seq);,那么你不会看到任何变化。确保您使用的是 new_thing = sorted(seq); print(new_thing) 或类似的。
  • o_O 您的代码对我来说似乎很好。请显示输入和预期输出?
  • 你能提供一个导致问题的示例列表吗?
  • 正如@Kevin 所说, sorted 不会改变一个列表,而是返回它的一个新版本。如果你想原地变异,你应该使用tupList.sort(key=lambda t: t[1])
  • @Kevin 你是对的。我从 list.sort() 切换到 sorted 并忘记了我必须将结果保存在某处。请回答,以便我接受。

标签: python list sorting tuples


【解决方案1】:

我猜你正在调用sorted,但没有在任何地方分配结果。比如:

tupList = [(2,16), (4, 42), (3, 23)]
sorted(tupList, key = lambda tup: tup[1])
print(tupList)

sorted 创建一个新的排序列表,而不是修改原始列表。试试:

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)

【讨论】:

    猜你喜欢
    • 2021-02-04
    • 2019-09-01
    • 2015-01-28
    • 2017-08-21
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多