如何在 Python 3 中使用 cmp()? [英] How to use cmp() in Python 3?

查看:75
本文介绍了如何在 Python 3 中使用 cmp()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法让命令 cmp() 工作.

I cannot get the command cmp() to work.

代码如下:

a = [1,2,3]
b = [1,2,3]
c = cmp(a,b)
print (c)

我收到错误:

Traceback (most recent call last):
  File "G:\Dropbox\Code\a = [1,2,3]", line 3, in <module>
    c = cmp(a,b)
 NameError: name 'cmp' is not defined
[Finished in 0.1s]

推荐答案

正如评论中提到的,cmp 在 Python 3 中不存在.如果你真的想要它,你可以自己定义它:

As mentioned in the comments, cmp doesn't exist in Python 3. If you really want it, you could define it yourself:

def cmp(a, b):
    return (a > b) - (a < b) 

取自原始 Python 3.0 的新功能.不过,这种情况非常罕见——尽管并非闻所未闻——但确实需要它,因此您可能需要考虑这是否真的是做任何事情的最佳方式.

which is taken from the original What's New In Python 3.0. It's pretty rare -- though not unheard of -- that it's really needed, though, so you might want to think about whether it's actually the best way to do whatever it is you're up to.

这篇关于如何在 Python 3 中使用 cmp()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆