2017-06-22 90 views
-3

有什麼方法可以使用任何返回變量?在Python中使用「any」返回變量?

不使用任何:

for punctuation in punctuations_list: 
    if punctuation in utterance: 
     print (punctuation) 

與任何(因爲標點符號得到錯誤將不會被初始化):

if any(punctuation in utterance for punctuation in punctuations_list): 
    print (punctuation) 

回答

3

沒有,any()只生產TrueFalse。如果您需要匹配的元素,請不要使用any(),而應使用過濾器(就像您使用for循環一樣)。

你可以使用列表理解首先要做到過濾:

matching = [p for p in puntuations_list if p in utterance] 
if matching: 
    # print all matching punctuation on separate lines 
    print(*matching, sep='\n') 

,或者如果你只需要第一匹配的元素,使用next() function和發電機的表達:

matching = next((p for p in puntuations_list if p in utterance), None) 
if matching is not None: 
    print(matching) 

如果生成器表達式不生成任何值,則返回next()的第二個參數;所以這裏None信號沒有匹配的標點符號(因此any()將返回False)。

+0

或'下一個()',如果他們只是想在第一次出現 –

+1

@Chris_Rands:這我不清楚他們期望的是什麼輸出;我添加了這個選項。 –

2

沒有,any()只能返回True的假,如果你需要一個變量使用filter()