是否可以使用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開始計數的單詞 位置的字符串)您的程序應該返回 假,如果目標單詞不串
'return [index for index,x in enumerate(sentence.split())if if == x]或False' – mshsayem
注意:顯式返回'False'是毫無意義的。只需返回listcomp本身;如果它是空的,它將表現爲一個虛假值,99%的時間,這是好的(或好於罰款,因爲它仍然像一個序列,所以你可以盲目地做一個for循環的結果和它根本不會做任何事情)。堅持實際的「真」/「假」值通常不是Pythonic,只是允許隱含的真實性測試來完成它的事情。 – ShadowRanger
爲什麼你認爲'False'比'[]'更好的返回值?在你應該使用布爾值的任何上下文中,一個空列表將被視爲「False」(並且我明確地將'foo == False'計數爲你應該*做的事情)。 – chepner