Python String - 将参数从列表传递给 .__contains__

Python String - Passing parameter to .__contains__ from a list

我有一个这样的字符串列表:

filterlist = ["Apple", "Banana", "Cherry"]

我想遍历它并检查这些字符串中的任何一个是否作为另一个字符串的一部分存在,例如

test_str = "An Apple a day keeps the Doctor away"

这是我尝试并成功的:

for f in filterlist:
    if test_str.__contains__(f):
        doSomething()

但我尝试执行以下操作但没有成功:

if test_str.__contains__(f for f in filterlist):
    doSomething()

第一种和第二种技术有什么区别? f for f in filterlist 是做什么的?

使用any

Return True if any element of the iterable is true. If the iterable is empty, return False.

>>> test_str = "An Apple a day keeps the Doctor away"
>>> filterlist = ["Apple", "Banana", "Cherry"]
>>> any(i in test_str for i in filterlist)
True

What does f for f in filterlist do?

这是一个generator expression,它创建了一个生成器对象:

>>> type(x for x in [])
<type 'generator'>

test_str.__contains__(f for f in filterlist) 从字面上看是在检查该生成器是否在 test_str* 中;其中,考虑到 你刚刚创建它,它不可避免地不会。

一样,使用 any 是将您的第一个代码转换为单行代码的正确方法。

* 注意 foo.__contains__(bar) 通常写成 bar in foo