首页 > 解决方案 > TypeError: sort() 没有位置参数

问题描述

我正在尝试将 Python2 代码更改为 Python3 代码。有类似的代码吗?

indice.sort(lambda x,y: -cmp(topic[x], topic[y]))

topic是一个浮动列表。 indicetopic的索引列表。喜欢:indice = list(range(len(topic))).

标签: pythonpython-3.x

解决方案


按照 λuser 在他们的评论中给出的链接,Python 3 (>= 3.2) 中的标准方法是使用functools.cmp_to_key

import functools
...
keyfunc = functools.cmp_to_key(lambda x,y: -cmp(topic[x], topic[y]))
indice.sort(key=keyfunc)

推荐阅读