Python中-1和False有区别吗?

发布于 2024-11-30 18:19:10 字数 815 浏览 0 评论 0原文

我一直认为在条件中使用 -1 总是与写入 False (布尔值)相同。但从我的代码中,我得到了不同的结果:

使用 True 和 False:

def count(sub, s):
    count = 0
    index = 0
    while True:
        if string.find(s, sub, index) != False:
            count += 1
            index = string.find(s, sub, index) + 1
        else:
            return count


print count('nana', 'banana')

结果:解释器需要很长时间才能响应。


使用 1 和 -1:

def count(sub, s):
    count = 0
    index = 0
    while 1:
        if string.find(s, sub, index) != -1:
            count += 1
            index = string.find(s, sub, index) + 1
        else:
            return count


print count('nana', 'banana')

结果:1​​

为什么使用 -1 和 1 给出正确的结果,而使用布尔值 True 和 False 则不能给出正确的结果?

I have always thought that using -1 in a condition is alway the same as the writing False (boolean value). But from my code, I get different results:

Using True and False:

def count(sub, s):
    count = 0
    index = 0
    while True:
        if string.find(s, sub, index) != False:
            count += 1
            index = string.find(s, sub, index) + 1
        else:
            return count


print count('nana', 'banana')

Result: Takes to long for interpreter to respond.


Using 1 and -1:

def count(sub, s):
    count = 0
    index = 0
    while 1:
        if string.find(s, sub, index) != -1:
            count += 1
            index = string.find(s, sub, index) + 1
        else:
            return count


print count('nana', 'banana')

Result: 1

Why does using -1 and 1 give me the correct result whereas using the bool values True and False do not?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

暗恋未遂 2024-12-07 18:19:11

False 的类型为 bool,它是 int 的子类型,其值为 0。

在 Python 中,False 类似于使用 0,而不是 -1

False is of type bool, which is a sub-type of int, and its value is 0.

In Python, False is similar to using 0, not -1

撞了怀 2024-12-07 18:19:11

出于历史和灵活性的原因,相等性和转换为布尔值以进行真值测试之间存在差异:

>>> True == 1
True
>>> True == -1
False
>>> bool(-1)
True
>>> False == 0
True
>>> bool(0)
False
>>> True == 2
False
>>> bool(2)
True

There's a difference between equality and converting to a boolean value for truth testing, for both historical and flexibility reasons:

>>> True == 1
True
>>> True == -1
False
>>> bool(-1)
True
>>> False == 0
True
>>> bool(0)
False
>>> True == 2
False
>>> bool(2)
True
墨洒年华 2024-12-07 18:19:11

我一直认为在条件中使用-1总是与写入False(布尔值)相同。

1)不。它从来都不一样,我无法想象为什么你会这么想,更不用说一直这么想了。除非由于某种原因你只使用过 ifstring.find 或其他东西。

2) 您一开始就不应该使用 string 模块。直接引用文档:

描述
警告:您在这里看到的大多数代码现在通常不被使用。
从 Python 1.6 开始,其中许多函数都实现为
标准字符串对象上的方法。它们曾经是由
一个名为 strop 的内置模块,但 strop 现在已经过时了。

因此,我们使用 str 类本身的 .find 方法( 'foobar''foo' 所属的类);因为我们有该类的对象,所以我们可以进行绑定方法调用,因此:'foobar'.find('foo')

3) 字符串的 .find 方法返回一个数字,告诉您在哪里找到子字符串(如果找到)。如果未找到子字符串,则返回 -1。在这种情况下它不能返回 0,因为这意味着“在开头找到”。

4) False 将比较等于 0。值得注意的是,Python 实际上将其 bool 类型实现为 int 的子类。

5) 无论您使用什么语言,都不应该与布尔文字进行比较。很简单,x == False 或等效内容是不正确的。它不会让你变得更加清晰,反而创造了犯错误的机会。

你永远不会用英语说“如果真的在下雨,我需要一把雨伞”,即使这在语法上是正确的。没有意义;这并不比显而易见的“如果下雨了,我需要一把雨伞”更礼貌,也更明确。

如果您想将值用作布尔值,则将其用作布尔值。如果您想使用比较的结果(即“该值是否等于-1?”),则执行比较。

I have always thought that using -1 in a condition is alway the same as the writing False (boolean value).

1) No. It is never the same, and I can't imagine why you would have ever thought this, let alone always thought it. Unless for some reason you had only ever used if with string.find or something.

2) You shouldn't be using the string module in the first place. Quoting directly from the documentation:

DESCRIPTION
Warning: most of the code you see here isn't normally used nowadays.
Beginning with Python 1.6, many of these functions are implemented as
methods on the standard string object. They used to be implemented by
a built-in module called strop, but strop is now obsolete itself.

So instead of string.find('foobar', 'foo'), we use the .find method of the str class itself (the class that 'foobar' and 'foo' belong to); and since we have objects of that class, we can make bound method calls, thus: 'foobar'.find('foo').

3) The .find method of strings returns a number that tells you where the substring was found, if it was found. If the substring wasn't found, it returns -1. It cannot return 0 in this case, because that would mean "was found at the beginning".

4) False will compare equal to 0. It is worth noting that Python actually implements its bool type as a subclass of int.

5) No matter what language you are using, you should not compare to boolean literals. x == False or equivalent is, quite simply, not the right thing to write. It gains you nothing in terms of clarity, and creates opportunities to make mistakes.

You would never, ever say "If it is true that it is raining, I will need an umbrella" in English, even though that is grammatically correct. There is no point; it is not more polite nor more clear than the obvious "If it is raining, I will need an umbrella".

If you want to use a value as a boolean, then use it as a boolean. If you want to use the result of a comparison (i.e. "is the value equal to -1 or not?"), then perform the comparison.

青瓷清茶倾城歌 2024-12-07 18:19:10

string.find 不会返回布尔值,因此 string.find('banana', 'nana', index)永远返回 0 (False) 无论值如何索引

>>> import string
>>> help(string.find)
Help on function find in module string:

find(s, *args)
    find(s, sub [, start [, end]]) -> int

    Return the lowest index in s where substring sub is found,
    such that sub is contained within s[start,end].  Optional
    arguments start and end are interpreted as in slice notation.

    Return -1 on failure.
>>>

您的示例只是重复:

index = string.find('banana', 'nana', 0) + 1 # index = 3
index = string.find('banana', 'nana', 3) + 1 # index = 0

-1 版本之所以有效,是因为它正确解释了 string.find 的返回值!

string.find doesn't return a boolean so string.find('banana', 'nana', index) will NEVER return 0 (False) regardless of the value of index.

>>> import string
>>> help(string.find)
Help on function find in module string:

find(s, *args)
    find(s, sub [, start [, end]]) -> int

    Return the lowest index in s where substring sub is found,
    such that sub is contained within s[start,end].  Optional
    arguments start and end are interpreted as in slice notation.

    Return -1 on failure.
>>>

Your example simply repeats:

index = string.find('banana', 'nana', 0) + 1 # index = 3
index = string.find('banana', 'nana', 3) + 1 # index = 0

The -1 version works because it correctly interprets the return value of string.find!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文