python - 显示 "if any"检测到的列表元素

标签 python string list if-statement

我正在使用一个简单的系统来检查字符串中当前是否有一些禁用词,但我想改进它以显示有问题的词,所以我添加了这一行

print ("BANNED WORD DETECTED : ", word)

但是我得到了错误

"NameError: name 'word' is not defined"

如果认为问题是我的系统只是检查列表中是否有任何单词而没有将其“存储”在某处,也许我误解了 python 列表系统,有什么建议我应该修改吗?

# -*- coding: utf-8 -*-

bannedWords = ['word1','word2','check']
mystring = "the string i'd like to check"

if any(word in mystring for word in bannedWords):
    print ("BANNED WORD DETECTED : ", word)
else :
    print (mystring)

最佳答案

any() 不适合这个,使用带有 next() 的生成器表达式代替或列表理解:

banned_word = next((word for word in mystring.split() if word in bannedWords), None)
if banned_word is not None:
   print("BANNED WORD DETECTED : ", word)

或者对于多个单词:

banned_words = [word for word in mystring.split() if word in bannedWords]
if banned_words:
    print("BANNED WORD DETECTED : ", ','.join(banned_words))

为了改进 O(1) 成员资格测试,将 bannedWords 设为 set 而不是 list

关于python - 显示 "if any"检测到的列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45689579/

相关文章:

python - Keras:过度拟合 Conv2D

python - 将属性添加到 Python 字典中的现有对象

c# - 无法从字符串中收集子字符串

python - Matplotlib:带有变量的图例条目

python - Python 2 和 Python 3 中 zip() 函数的区别

python - 有没有办法比较阿拉伯字符而不考虑它们的初始/中间/最终形式?

java - 如何使用 Gson 将 JSON 字符串属性读取到自定义类对象中?

python - 如何让 Python 输入循环读取和更新列表项

python - 根据另外 2 个列表的索引比较 2 个列表,并使用列表理解将索引保存在新列表中

Sharepoint XSL 数据 View 查询字符串过滤