簡體   English   中英

為什么我的if語句不起作用?

[英]Why is my if statement is not working?

為什么我的代碼底部的if語句不起作用? 單詞列表包含多個“測試”,但是if語句下面的print語句不起作用。

text1 = "a"
text2 = "b"
text3 = "c"
words = []
if len(text1) < 2:
    words.append('test11')
elif text1.isspace():
    words.append('test12')
if len(text2) < 2:
    words.append('test21') 
elif text2.isspace():
    words.append('test22')
if len(text3) < 2:
    words.append('test31')
elif text3.isspace():
    words.append('test32')
if "test" in words:
    print "Test"

在前三個if語句結束時,您具有:

words = ['test11', 'test21', 'test31']

通過使用in來檢查'test'出現在words數組中,實際上是將'test'與單詞中的每個單詞進行比較:

'test11' == 'test'  # False
'test21' == 'test'  # False
'test31' == 'test'  # False

所以很明顯它應該返回False 你需要做的是檢查,如果'test'出現的任何的的話words

for word in words:
    if 'test' in word:
        print("Test")
        break

或更Python地:

if any(["test" in word for word in words]):
    print("Test")

也許您想要一些可以測試單詞test是否在words列表中列出的字符串中的東西:

text1 = "a"
text2 = "b"
text3 = "c"
words = []
if len(text1) < 2:
    words.append('test11')
elif text1.isspace():
    words.append('test12')
if len(text2) < 2:
    words.append('test21') 
elif text2.isspace():
    words.append('test22')
if len(text3) < 2:
    words.append('test31')
elif text3.isspace():
    words.append('test32')
for i in words:
    if "test" in i:
        print "Test"
        break

“ test”本身是一個完整的字符串,不在列表中,如果您在列表的元素內進行比較,則該字符串為true。

validity = map(lambda x: 'test' in x, words)
if True in validity:
    print "Test"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM