且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python比较两个列表中的元素

更新时间:2022-11-17 14:19:29

现在您已经解决了原来的问题,并修复了向后执行检查的下一个问题,更改了您的所有变量,您可以这样做:

Now that you've fixed the original problem, and fixed the next problem with doing the check backward, and renamed all of your variables, you have this:

for match in dictionary:
    if any(match in value for value in sentences):
        print match

您的问题是:


我有代码写我可以得到字典项目,而是我想打印的句子。

The way I have the code written i can get the dictionary items but instead i want to print the sentences.

嗯,是的,你的匹配是一个字典项,这就是你正在打印,所以当然这就是你所得到的。

Well, yes, your match is a dictionary item, and that's what you're printing, so of course that's what you get.

如果你想打印包含字典项的句子,你不能使用 any ,因为整点的功能我们只要返回True,如果任何元素是真的。它不会告诉你哪些 - 其实,如果有不止一个,它会在第一个停止。

If you want to print the sentences that contain the dictionary item, you can't use any, because the whole point of that function us to just return True if any elements are true. It won't tell you which ones—in fact, if there are more than one, it'll stop at the first one.

如果你不明白功能像任何和您传递给他们的生成器表达式,您真的不应该将它们用作魔术调用。找出如何将它们写成显式循环,您将能够轻松地回答这些问题。 (请注意,任何文档直接显示如何编写等效循环。)

If you don't understand functions like any and the generator expressions you're passing to them, you really shouldn't be using them as magic invocations. Figure out how to write them as explicit loops, and you will be able to answer these problems for yourself easily. (Note that the any docs directly show you how to write an equivalent loop.)

例如,您现有的代码相当于:

For example, your existing code is equivalent to:

for match in dictionary:
    for value in sentences:
        if match in value:
            print match
            break

这样写就应该很明显如何解决它首先,您要打印句子而不是单词,因此打印而不是匹配(再次,它如果您使用有意义的变量名称(如句子字词而不是无意义的名称,如价值和误导性名称,如 match ...)。其次,您要打印所有匹配的句子,而不仅仅是第一个,所以不要 break 。所以:

Written that way, it should be obvious how to fix it. First, you want to print the sentence instead of the word, so print value instead of match (and again, it would really help if you used meaningful variable names like sentence and word instead of meaningless names like value and misleading names like match…). Second, you want to print all matching sentences, not just the first one, so don't break. So:

for match in dictionary:
    for value in sentences:
        if match in value:
            print value

如果你回到我的第一个答案,你可能会注意到这是我建议的结构完全相同。

And if you go back to my first answer, you may notice that this is the exact same structure I suggested.

您可以通过使用理解和迭代函数来简化或缩短这一点,但直到您了解简单版本,以及这些理解和迭代功能如何工作。

You can simplify or shorten this by using comprehensions and iterator functions, but not until you understand the simple version, and how those comprehensions and iterator functions work.