确定一个列表中的字符串是否存在于另一个字符串列表中

时间:2016-04-09 21:44:59

标签: python string for-loop

我正在处理一个问题,我需要查看段落中的项目并识别出未知的单词"。我有两个清单。

第一篇(文章): ["this","is","a","test","does","it","work"]

"已知"话: ["this","is","a","test"]

我是Python中的基本编码器,因此我尝试使用嵌套的for循环,浏览段落列表中的项目,并根据"已知&#34中的单词检查它们;列表,但我遇到了一些问题。

for word in passage:
    for word1 in known:
        if word == word1:
            print word + " "
        else:
            print "* " + word + " * "   

预期结果为>>>"this is a test * does * * it * * work *"

3 个答案:

答案 0 :(得分:1)

试试这个:

def identify(passage, known_words):
    result = [i if i in known_words else "* " + i + " *" for i in passage]
    return " ".join(result)

结果:

>>> identify(["this","is","a","test","does","it","work"], ["this","is","a","test"])
'this is a test * does * * it * * work *'

答案 1 :(得分:1)

我想我应该把我的评论作为答案。 Python有一个很好的功能;即您已在两个in循环中使用的关键字forin还允许您在列表,元组或字典中搜索变量,短语等的存在。不使用使用显式for循环。 所以而不是:

for word in passage:
    for word1 in known:
       ...

您可以简单地写一下:

for word in passage:
    # here, python will search the entire list (known) for word
    if word in known:
        print word + " "
    else:
        print "* " + word + " * " 

答案 2 :(得分:0)

passage = ['this','is','a','test','does','it','work']
known_words = ['this','is','a','test']
new_string = []
for word in passage:
    if word in known_words:
        new_string.append(word + " ")
    else:
        new_string.append("* " + word + " * ")

print ''.join(new_string)

输出:this is a test * does * * it * * work *