【问题标题】:"in" statement behavior in lists vs. strings列表与字符串中的“in”语句行为
【发布时间】:2013-08-19 02:58:38
【问题描述】:

在 Python 中,询问字符串中是否存在子字符串非常简单:

>>> their_string = 'abracadabra'
>>> our_string = 'cad'
>>> our_string in their_string
True

但是,检查这些相同的字符是否“在”列表中失败:

>>> ours, theirs = map(list, [our_string, their_string])
>>> ours in theirs
False
>>> ours, theirs = map(tuple, [our_string, their_string])
>>> ours in theirs
False

我找不到任何明显的原因,为什么检查“在”有序(甚至不可变)迭代中的元素与不同类型的有序、不可变迭代的行为不同。

【问题讨论】:

    标签: python substring iterable in-operator


    【解决方案1】:

    对于列表和元组等容器类型,x in container 检查x 是否是容器中的项目。因此,对于 ours in theirs,Python 会检查 ours 是否是 theirs 中的一个项目,并发现它是 False。

    请记住,一个列表可以包含一个列表。 (例如[['a','b','c'], ...]

    >>> ours = ['a','b','c']    
    >>> theirs = [['a','b','c'], 1, 2]    
    >>> ours in theirs
    True
    

    【讨论】:

    • type(ours) != type(theirs[0])type(our_string) == type(their_string[0])。谢谢。
    【解决方案2】:

    您是否要查看“cad”是否在字符串列表中的任何字符串中?那会是这样的:

    stringsToSearch = ['blah', 'foo', 'bar', 'abracadabra']
    if any('cad' in s for s in stringsToSearch):
        # 'cad' was in at least one string in the list
    else:
        # none of the strings in the list contain 'cad'
    

    【讨论】:

      【解决方案3】:

      来自 Python 文档,https://docs.python.org/2/library/stdtypes.html 用于序列:

      x in s  True if an item of s is equal to x, else False  (1)
      x not in s  False if an item of s is equal to x, else True  (1)
      
      (1) When s is a string or Unicode string object the in and not in operations act like a substring test.
      

      对于用户定义的类,__contains__ 方法实现了这个in 测试。 listtuple 实现了基本概念。 string 添加了“子字符串”的概念。 string 是基本序列中的一个特例。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-09
        • 1970-01-01
        • 2013-11-14
        • 2012-12-21
        相关资源
        最近更新 更多