2011-08-21 31 views
0

我一直認爲在條件中使用-1總是與寫作False(布爾值)相同。但是從我的代碼,我得到不同的結果:在Python中,-1和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不要?

+0

[爲什麼1 == True但是2!= True在Python?](http://stackoverflow.com/questions/7134984/why-does-1-true-but-2-true-in -python) – agf

+0

我們剛剛在Python中提出了一個關於'True'和'False'的問題。 '-1'在Python中不是'False','0'是False。在發佈問題之前,請搜索這樣的內容。 – agf

+0

另請參閱[python-true-false](http://stackoverflow.com/questions/5119709/python-true-false),[why-cant-python-handle-true-false-values-as-i-expect ](http://stackoverflow.com/questions/2055029/why-cant-python-handle-true-false-values-as-i-expect),[is-false-0-and-true-1-in-蟒-AN-實現細節或 - 是 - 它擔保](http://stackoverflow.com/questions/2764017/is-false-0-and-true-1-in-python-an-implementation-detail -or-it-it-guarantee),[true-false-true] – agf

回答

3

string.find沒有返回一個布爾所以string.find('banana', 'nana', index)NEVER換貨政... 0False),無論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. 
>>> 

你舉的例子只是重複:

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

-1版本的作品,因爲它正確解釋的string.find返回值!

+0

+1用於引用文檔!但請引用你的消息來源。 –

+0

'False == 0'產生'True'。 –

2

假是bool類型,這是一個子int類型的,並且其值爲0

在Python,False類似於使用0,而不是-1

1

有之間的差平等和轉換爲實況測試一個布爾值,歷史和靈活性方面的原因:

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

我一直認爲在條件使用-1常是一樣的書寫假(布爾值)。

1)不,這是永遠不變的,我無法想象爲什麼你會想到這一點,更別說總是這樣想了。除非由於某種原因,否則你只使用ifstring.find什麼的。

2)您不應該首先使用string模塊。直接從文檔報價:

說明
警告:最讓你看到這裏通常不採用時下的代碼。 從Python 1.6開始,許多這些函數在標準字符串對象上實現爲 方法。他們以前通過一個名爲strop的內置模塊來實現 ,但strop現在已經過時。

所以不是string.find('foobar', 'foo'),我們使用str類本身(類'foobar''foo'屬於)的.find方法;並且由於我們有該類的對象,所以我們可以進行綁定方法調用,因此:'foobar'.find('foo')

3)字符串的.find方法返回一個數字,告訴你在哪裏找到子字符串,如果找到了。如果未找到子字符串,則返回-1。在這種情況下它不能返回0,因爲這意味着「在開始時被發現」。

4)False將比較等於0。值得注意的是,Python實際上實現了bool類型作爲int的子類。

5)無論您使用何種語言,都不應與布爾文字進行比較。很簡單,x == False或等價物是不正確的。它在清晰度方面沒有任何收穫,並創造出錯機會。

你永遠不會說「如果這是真的,它正在下雨,我將需要一把傘」,儘管這在語法上是正確的。無關緊要;它不比更明顯的「如果下雨,我需要一把雨傘」更有禮貌,也不更清晰。

如果要將值用作布爾值,則將其用作布爾值。如果您想要使用比較結果(即「是等於-1還是不是?」),則執行比較。

相關問題