在处理来自 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, 3)
变成(3, (1, 3))
,将每个tuple
包装在一个新的元组中, 以及您要首先排序的项目。 - 您使用外部
tuple
进行排序,确保原始tuple
中的第二项首先排序。 - 您从
(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/