Python: PHP "==" 的等效是什么

5 投票
8 回答
685 浏览
提问于 2025-04-18 04:27

问题已经说得很清楚了。

这里简单解释一下。

在PHP中,"=="的用法是这样的:

2=="2" (Notice different type)
// True

而在Python中:

2=="2"
// False
2==2
// True

在PHP中,和Python的"=="相对应的是"==="。

2===2
//True
2==="2"
//False

关键问题来了。PHP中的"=="在Python中对应的是什么呢?

8 个回答

0

这里是和PHP中的==相等的东西。

def php_cmp(a, b):
    if a is None and isinstance(b, basestring):
        a = ""
    elif b is None and isinstance(a, basestring):
        b = ""
    if a in (None, False, True) or b in (None, False, True):
        return bool(a) - bool(b)
    if isinstance(a, (basestring, int, long, float)) and isinstance(b, (basestring, int, long, float)):
        try:
            return cmp(float(a), float(b))
        except ValueError:
            return cmp(a,b)
    if isinstance(a, (tuple,list)) and isinstance(b, (tuple,list)):
        if len(a) != len(b):
            return cmp(len(a),len(b))
        return cmp(a,b)
    if isinstance(a, dict) and isinstance(b, dict):
        if len(a) != len(b):
            return cmp(len(a),len(b))
        for key in a:
            if key not in b:
                raise AssertionError('not compareable')
            r = cmp(a[key], b[key])
            if r: return r
        return 0
    if isinstance(a, (basestring, int, long, float)):
        return 1
    if isinstance(b, (basestring, int, long, float)):
        return -1
    return cmp(a,b)

def php_equal(a, b):
    return php_cmp(a,b) == 0

测试:

>>> php_equal(2, '2')
True

由于不同的对象模型和数组实现,这个并不是100%准确,但应该能让你了解在自动转换类型进行比较时可能会出现的一些问题。

1

你也可以这样做

str(2) == "2"
1

没有直接对应的东西。

主要的区别在于,Python是强类型语言,而PHP则不是。所以在Python中,如果你比较两种不同类型的数据,结果总是会返回假(false)。当然,如果你明确地把其中一种类型转换成另一种类型,那就另当别论了。

6

没有一种简单的方法。你需要在检查是否相等之前先转换数据类型。在你的例子中,你可以这样做:

2==int("2")
7

Python在类型转换方面和PHP不太一样,大多数情况下,它不会自动转换。

你需要自己明确地进行转换:

2 == int('2')

或者

str(2) == '2'

不过,Python会在数字类型之间进行转换(比如你可以把一个浮点数和一个整数进行比较),而在Python 2中,它还会自动在Unicode和字节字符串之间转换(这让很多人感到困扰)。

撰写回答