[英]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.