2017-04-19 102 views
-1

爲什麼我的代碼底部的if聲明不起作用? 單詞列表包含幾個「測試」,但在if聲明下方的打印語句不起作用。爲什麼我的if語句不起作用?

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" 
+0

你'if'聲明是工作的罰款。沒有任何內容被打印出來,因爲你的清單「words」不包含字符串「test」。 – timgeb

+0

「詞」列表中不包含確切的單詞'「test」'。可能是你用字符串 – kuro

+2

混淆了這個,因爲''test''不在'單詞'中,它在單詞的一些單詞中,而不是單詞本身。你可以使用:'如果有的話([「用單詞測試」)''。雖然這有點羅嗦。 –

回答

3

通過你的第一個3所if陳述結束時,您有:

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

通過使用in來檢查,如果數組words內發生'test',它實際上是做什麼用的每個詞比較'test'用文字表示:

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

所以很清楚它應該返回False。你需要做的是檢查中的任何的話出現在'test'words

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

或者更pythonically:

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

也許你想要的測試,如果字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 
0

「測試」本身是一個完整的字符串,它是不存在的列表中,如果您在列表中的元素內進行比較,它將是真實的。

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