python - 在 Python 中对元组列表进行排序

标签 python

在处理来自 Google Python 类的问题时,我使用 Stack overflow 中的 2-3 个示例制定了以下结果-

def sort_last(tuples):
    return [b for a,b in sorted((tup[1], tup) for tup in tuples)]

print sort_last([(1, 3), (3, 2), (2, 1)])

我昨天学习了列表推导,所以对列表推导略知一二,但我对这个解决方案的整体工作方式感到困惑。请帮助我理解这一点(功能中的第二行)。

最佳答案

该模式称为装饰-排序-取消装饰。

  1. 将每个 (1, 3) 变成 (3, (1, 3)),将每个 tuple 包装在一个新的元组中, 以及您要首先排序的项目。
  2. 您使用外部 tuple 进行排序,确保原始 tuple 中的第二项首先排序。
  3. 您从 (3, (1, 3)) 返回到 (1, 3),同时保持列表的顺序。

在 Python 中,显式装饰几乎总是不必要的。相反,使用 key argument of sorted :

sorted(list_of_tuples, key=lambda tup: tup[1]) # or key=operator.itemgetter(1)

或者,如果您想对 tuple 的反向版本进行排序,无论其长度如何:

sorted(list_of_tuples, key=lambda tup: tup[::-1]) 
                              # or key=operator.itemgetter(slice(None, None, -1))

关于python - 在 Python 中对元组列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10213994/

相关文章:

python - 如何避免在 PyTest 中从 session 范围固定装置中改变对象?

python - 使用请求 python 发布复杂数据字典

python - 数据库优先 Django 模型

python - 为什么在使用 NumPy 进行楼层划分时会显示数据类型(即使它是 native 数据类型)?

带逗号的 Python 数组切片?

python - 如何从特定格式的 DataFrame 创建稀疏矩阵

python - 将列表转换为 numpy 数组导致比预期大得多的内存

python - 如何在 python 中从 ndarray 中选择 n 项并跳过 m?

python - 在 python 中使用 Iterable 和 numeric 作为函数的输入

python - 在 webpy 上只初始化一次 python 类