Python 中的 sort() 使用 cmp

sort() in Python using cmp

我正在尝试对列表进行排序,将所有 0 移到列表末尾。 示例:[0,1,0,2,3,0,4]->[1,2,3,4,0,0,0]

我看到有人用 1 行代码

list.sort(cmp=lambda a,b:-1 if b==0 else 0)

但是我不明白括号里面是什么意思。

谁能告诉我?谢谢。

前言:

Sort a list according to the normal comparison:

some_list.sort()   

提供 custom comparator:

some_list.sort(cmp=my_comparator)

A lambda function:

x = lambda a, b: a - b
# is roughly the same as
def x(a, b):
    return a - b

一个if-else-expression:

value = truthy_case if condition else otherwise
# is roughly the same as
if condition:
    value = truthy_case
else:
    value = otherwise

list.sort(cmp=lambda a,b:-1 if b==0 else 0)行本身:

现在比较器中的条件是是否b==0,如果是则说明b的值大于a(结果的符号为负),否则表示值比较相同(符号为零)。

虽然Python的list.sort()stable这段代码不合理,因为比较器需要测试a,也不仅仅是b。正确的实现将使用 key 参数:

some_list.sort(key=lambda a: 0 if a == 0 else -1)

固定 list.sort(cmp=...) 实现:

如果你想使用 list.sort(cmp=...)(你不需要)或者如果你只是好奇,这是一个合理的实现:

some_list.sort(cmp=lambda a, b: 0 if a == b else
                               +1 if a == 0 else
                               -1 if b == 0 else 0)

But notice:

In Py3.0, the cmp parameter was removed entirely (as part of a larger effort to simplify and unify the language, eliminating the conflict between rich comparisons and the __cmp__ methods).

备选方案:

列表排序在 O( log ) 中进行。我不知道对于这个简单的问题代码是否运行得更快,但我不这么认为。 O() 解决方案正在过滤:

new_list = [x for x in some_list if x != 0]
new_list.extend([0] * (len(some_list) - len(new_list)))

不过,差异可能只对相当长的列表有影响。

>>> sorted(l, key=lambda x:str(x) if x == 0 else x)
[1, 3, 4, 8, 0, 0, 0]

猜猜这里发生了什么?我正在利用这样一个事实,即作为偏好,python 将首先选择整数,然后是字符串。所以我将 0 转换为“0”。

这是证明。

>>> ll = [3,2,3, '1', '3', '0']
>>> sorted(ll)
[2, 3, 3, '0', '1', '3']

你应该自己回答,这是计划:


此处提供三元表达式说明:

https://docs.python.org/3/reference/expressions.html?highlight=ternary%20operator#conditional-expressions

你可以在该文档中找到很多表达式描述:

https://docs.python.org/3/reference/expressions.html


问:lambda 是什么意思?

请花 5 天时间阅读关于 Python 语言的教程,它是 Gvinno Van Rossum 原著的分支。

https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions