【问题标题】:Python String - Passing parameter to .__contains__ from a listPython String - 从列表中将参数传递给 .__contains__
【发布时间】:2015-08-04 07:48:16
【问题描述】:

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

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 是做什么的?

【问题讨论】:

    标签: python string list contains


    【解决方案1】:

    使用any

    如果可迭代的任何元素为真,则返回真。如果 iterable 为空,则返回 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
    

    【讨论】:

    • 您的意思是使用any 代替__contains__ 吗?
    • 严格来说,您使用的是in 而不是__contains__ - 这可以写成any(test_str.__contains__(i) for i in filterlist)any 正在替换 for 循环。
    • @jonrsharpe,谢谢!这清除了一切:)
    【解决方案2】:

    f for f in filterlist 是做什么的?

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

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

    test_str.__contains__(f for f in filterlist) 实际上是在检查该生成器是否在test_str* 中;鉴于你只是刚刚创建它,它不可避免地不会是。

    作为Avinash has pointed out,使用any 是将您的第一个代码转换为单行的正确方法。

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

    【讨论】:

      猜你喜欢
      • 2022-01-08
      • 2015-11-20
      • 1970-01-01
      • 2021-06-01
      • 2019-03-02
      • 1970-01-01
      • 2014-04-06
      • 2015-06-06
      • 2017-02-18
      相关资源
      最近更新 更多