Python 如何查找列表的一部分是否在str中
我想做一个审查员。而不是做Python 如何查找列表的一部分是否在str中,python,loops,Python,Loops,我想做一个审查员。而不是做 if curseword in typed or curseword2 in typed or curseword3 typed: print "No cursing! It's not nice!" 我想制作一个包含所有单词的列表,并检查这些单词是否在列表中。注意:如果您使用带有while循环的“if any…”代码,则它有太多的输出要处理。您可以使用any加上生成器: cursewords = ['javascript', 'php', 'windows
if curseword in typed or curseword2 in typed or curseword3 typed:
print "No cursing! It's not nice!"
我想制作一个包含所有单词的列表,并检查这些单词是否在列表中。注意:如果您使用带有while循环的“if any…”代码,则它有太多的输出要处理。您可以使用
any
加上生成器:
cursewords = ['javascript', 'php', 'windows']
if any(curseword in input for curseword in cursewords):
print 'onoes'
或者,为了更加灵活,可以使用正则表达式(如果您还想检测大写诅咒词):
(如果您是regex新手,)
如果您只想忽略case而不想弄乱regexen,您也可以这样做:
# make sure these are all lowercase
cursewords = ['javascript', 'php', 'windows']
input_lower = input.lower()
if any(curseword in input_lower for curseword in cursewords):
print 'onoes'
在输入端使用for循环,检查每个单词是否在cursewords列表中
cursewordList = ['a','b' ...]
for word in input:
if word in cursewordList:
print "No cursing! It's not nice!"
使用、过滤以及内置方法:
>>>test = ['ONE', 'TWO', 'THREE', 'FOUR']
>>>input = 'TWO'
>>> if filter(lambda s: s in input, test):
print 'OK'
OK
>>> input = 'FIVE'
>>>
>>> if filter(lambda s: s in input, test):
print 'OK'
>>> #nothing printed
“代码必须与while循环兼容”到底是什么意思?@SiHa我的意思是,如果代码中有for,它将无休止地输出并破坏整个世界。我需要它不要有for循环,否则会发生这种情况。我敢肯定这是因为你没有正确地实现它。你的可能副本可能会通过这种方式得到一些误报-但它并不像Clbuttic错误地使用正则表达式那样糟糕,使用
“|”。join(cursewords)
那么我们不需要手动从列表中键入这些单词:)@KevinGuan可能不是个好主意,如果“诅咒单词”包含正则表达式特殊字符怎么办?最好只使用一个正则表达式,这样您也可以使用java(script)
@KevinGuan不,您需要'|'。join(map(re.escape,cursewords))
。否则你就是在逃避
s.@虽然我不知道你想说什么。这不是一个无限循环。@Ough我。。。我还是不知道你在说什么。也许这会更好,因为一个单独的问题包括重现问题所需的所有代码。这种方式具有更好的大O复杂性-如果您将cursewordList设置为集
。解决方案可行,但它会扫描每个诅咒词,即使它已经找到了一个。
>>>test = ['ONE', 'TWO', 'THREE', 'FOUR']
>>>input = 'TWO'
>>> if filter(lambda s: s in input, test):
print 'OK'
OK
>>> input = 'FIVE'
>>>
>>> if filter(lambda s: s in input, test):
print 'OK'
>>> #nothing printed