2017-10-12 57 views
1

是否可以使用if語句中的if/else語句將方法find_indexes中的行數減少爲1行?在if/else語句中測試空列表理解

def find_indexes(sentence, target): 
    indexes = [index for index, x in enumerate(sentence.split()) if target == x] 

    return indexes if indexes else False 

target = 'dont' 
sentence = 'we dont need no education we dont need no thought control no we dont' 

print(find_indexes(sentence, target)) 
>> [1, 6, 13] 
print(find_indexes(sentence, 'johndoe')) 
>> False 

我期待的方法改變這樣的事情,而不需要寫兩次的理解:

def find_indexes(sentence, target): 
    return [index for index, x in enumerate(sentence.split()) if target == x] \ 
     if [index for index, x in enumerate(sentence.split()) if target == x] else False 

編寫需要用空格分隔一串字的程序 (假設沒有標點符號或大寫字母)連同「目標」字 ,並顯示目標字在 字符串中的位置。

例如,如果字符串是:

我們不需要沒有教育我們不需要任何思想控制,不,我們不

,目標就是兩個字:

「不」

然後你的程序應該返回列表1,6,13,因爲「dont」在字符串中的第1,6和13位出現 。 (我們開始從0開始計數的單詞 位置的字符串)您的程序應該返回 假,如果目標單詞不串

+1

'return [index for index,x in enumerate(sentence.split())if if == x]或False' – mshsayem

+3

注意:顯式返回'False'是毫無意義的。只需返回listcomp本身;如果它是空的,它將表現爲一個虛假值,99%的時間,這是好的(或好於罰款,因爲它仍然像一個序列,所以你可以盲目地做一個for循環的結果和它根本不會做任何事情)。堅持實際的「真」/「假」值通常不是Pythonic,只是允許隱含的真實性測試來完成它的事情。 – ShadowRanger

+5

爲什麼你認爲'False'比'[]'更好的返回值?在你應該使用布爾值的任何上下文中,一個空列表將被視爲「False」(並且我明確地將'foo == False'計數爲你應該*做的事情)。 – chepner

回答

3

您可以短路與or

def find_indexes(sentence, target): 
    return [i for i, x in enumerate(sentence.split()) if target == x] or False 
3
return [...] or False 

or運算符返回其操作數中的一個出現;第一個如果第一個是真的,否則第二個。

4

只返回空列表,如果沒有找到的匹配。

def find_indexes(sentence, target): 
    return [index for index, x in enumerate(sentence.split()) if target == x] 

indices = find_indexes("hi there bob", "bob") 
if not indices: 
    print("No matches found") 
else: 
    for i in indices: 
     print("Found match at {}".format(i)) 
+0

確實。我認識到它是「是」這個詞,但沒有采取下一步來記住它是一個關鍵字。 – chepner

1

返回False不僅毫無意義,而且使代碼更大更脆弱。

每次使用原始find_indexes函數時,都需要檢查它是布爾值還是列表。否則,如果沒有索引中找到你的代碼可能會引發一個TypeError

def find_indexes(sentence, target): 
    indices = [index for index, x in enumerate(sentence.split()) if target == x] 
    return indices if indices else False 

sentence = 'we dont need no education we dont need no thought control no we dont' 

for index in find_indexes(sentence, "not_found"): 
    print(index) 

它拋出:

TypeError: 'bool' object is not iterable 

至於建議的@chepner,只是如果沒有索引被發現返回一個空列表:空列表無論如何,它在Python中都是虛假的。你的功能和後續的呼叫需要少一條線。

最後,由於Python是一種動態語言,因此使用適當的函數名稱來編寫可讀代碼非常重要。如果你的函數被稱爲find_indexes,它應該返回一個迭代。如果它叫is_a_substring,那麼它應該返回一個布爾值。