Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 确定一个列表中的字符串是否存在于另一个字符串列表中_Python_String_For Loop - Fatal编程技术网

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

Python 确定一个列表中的字符串是否存在于另一个字符串列表中,python,string,for-loop,Python,String,For Loop,我正在解决一个问题,我需要浏览一篇文章的各个部分,找出“未知”的单词。我有两张单子 第一段: [“这”、“是”、“a”、“测试”、“做”、“它”、“工作”] 以及“已知”单词列表: [“这”、“是”、“a”、“测试”] 我在Python中是一个相当初级的程序员,所以我尝试使用嵌套for循环,查看段落列表中的项目,对照“已知”列表中的单词检查它们,但我面临一些问题 for word in passage: for word1 in known: if word == wor

我正在解决一个问题,我需要浏览一篇文章的各个部分,找出“未知”的单词。我有两张单子

第一段:
[“这”、“是”、“a”、“测试”、“做”、“它”、“工作”]

以及“已知”单词列表:
[“这”、“是”、“a”、“测试”]

我在Python中是一个相当初级的程序员,所以我尝试使用嵌套for循环,查看段落列表中的项目,对照“已知”列表中的单词检查它们,但我面临一些问题

for word in passage:
    for word1 in known:
        if word == word1:
            print word + " "
        else:
            print "* " + word + " * "   
预期结果将是
>>“这是一个测试*做**它**工作*”

输出:
这是一个测试*做**它**工作*

试试这个:

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 *'

我想我的评论应该是一个答案。Python有一个整洁的特性;即中的关键字
,您已经在
的两个
循环中使用了该关键字。
中的
还允许您搜索列表、元组或字典中是否存在变量、短语等,而无需使用显式的
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 + " * " 

你有什么问题?python有一个简洁的特性:
for word in known:if word in passion:…
那么你可以避免第二个
for
循环和
=
for word in passage:
    # here, python will search the entire list (known) for word
    if word in known:
        print word + " "
    else:
        print "* " + word + " * "