2017-04-19 101 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"