Python 为什么我的if语句不起作用?
为什么代码底部的Python 为什么我的if语句不起作用?,python,python-2.7,if-statement,Python,Python 2.7,If Statement,为什么代码底部的if语句不起作用? 单词列表包含几个“test”,但是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') e
if
语句不起作用?
单词列表包含几个“test”,但是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"
text1=“a”
text2=“b”
text3=“c”
单词=[]
如果len(text1)<2:
words.append('test11')
elif text1.isspace():
words.append('test12')
如果len(text2)<2:
words.append('test21')
elif text2.isspace():
words.append('test22')
如果len(text3)<2:
words.append('test31')
elif text3.isspace():
words.append('test32')
如果“测试”用文字表示:
打印“测试”
如果单词test
位于单词
列表中列出的字符串中,您可能需要一些测试:
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
text1=“a”
text2=“b”
text3=“c”
单词=[]
如果len(text1)<2:
words.append('test11')
elif text1.isspace():
words.append('test12')
如果len(text2)<2:
words.append('test21')
elif text2.isspace():
words.append('test22')
如果len(text3)<2:
words.append('test31')
elif text3.isspace():
words.append('test32')
对于我来说,用文字来说:
如果i中的“测试”:
打印“测试”
打破
“test”本身是列表中不存在的完整字符串,如果在列表的元素中进行比较,则为true
validity = map(lambda x: 'test' in x, words)
if True in validity:
print "Test"
在前3个
if
语句结束时,您有:
words = ['test11', 'test21', 'test31']
通过使用中的检查'test'
是否出现在数组单词中,它实际做的是将'test'
与单词中的每个单词进行比较:
'test11' == 'test' # False
'test21' == 'test' # False
'test31' == 'test' # False
因此,它显然应该返回False
。您需要做的是检查“测试”
是否出现在单词中的任何单词中:
for word in words:
if 'test' in word:
print("Test")
break
或者更像蟒蛇:
if any(["test" in word for word in words]):
print("Test")
您的if
语句工作正常。没有打印任何内容,因为列表单词
不包含字符串“test”
。列表单词
不包含确切的单词“test”
。您可能会将其与string混淆,因为“test”
不在单词中,而是在单词中的一些单词中,而不是单词本身。您可以改为使用:如果有的话([“test”在words中逐字逐句])
。虽然这有点冗长。因为您的列表words=['test11','test21','test31']
,所以不完全是test
。谢谢您的帮助。我已经用for语句解决了这个问题。