查看列表中的项是否在Python中的另一项中

时间:2013-07-23 08:44:33

标签: python

我是编程新手,刚开始学习Python。我想创建一个小程序,它只是检测你是否输入了一个“坏词”。

name = input ('Please enter your name. ')
badword=['foo', 'bar']
if name in badword:
    print ('No.')
else:
    print ('Yes')

这种方式不起作用,因为它占用了输入的全部内容,并且正在搜索该条目的列表。如果我向我们试试:

if badword in name:

然后我得到一个错误。我可以调用列表的每个部分,但这是很多代码,特别是如果你输入不同类型的坏词,而这对于我知道我可以用更少的代码做的事情来说会变得冗长。在这里有点迷失,谷歌搜索已经枯竭。

3 个答案:

答案 0 :(得分:5)

您需要遍历badword列表以测试每个单词

for word in badword:
    if word in name:
        print('No.')
        break
else:
    print('Yes.')

else子句是for语句的一部分;当循环break语句中断时执行它,因此在这种情况下,如果badword中没有任何值匹配。

这可以通过any() function和生成器表达式缩短:

if any(word in name for word in badword):
    print('No.')
else:
    print('Yes.')

答案 1 :(得分:1)

您的第二次尝试:if badword in name几乎是正确的。您需要检查badword中的每个项目 - 如下所示:

if any( [ word for word in badword if word in name ] ):
    print( 'No' )
    break
else:
    print( 'Yes' )
如果任何条件匹配,

any将返回true。 []之间的位是列表推导,它返回一个新列表。 e.g:

print( [ word for word in badword ] )

最后if word in name是addign项目添加到新列表的条件,因此只有条件为True的项目才会在新列表中结束。

答案 2 :(得分:0)

inputs = [" some BAD sentense ", "some right sentense"]
bad_words_list = ["bad", "wrong"]

def check(enter):
    """Check for word in bad words list. Note, check process not key sensitive.

    Return True if sentense contains bad word."""
    sentense = enter.lower().split()
    for word in bad_words_list:
        if word.lower() in sentense:
            return False
    return True

print "Is sentense bad? " + str(check(inputs[0]))
print "Is sentense bad? " + str(check(inputs[1]))

测试它:

$ python test.py
Is sentense bad: False
Is sentense bad: True