【问题标题】:'in' operator: text containing words versus list of words'in' 运算符:包含单词的文本与单词列表
【发布时间】:2016-07-20 12:39:06
【问题描述】:

为什么下面的示例 3(使用 text.split())会产生正确的结果,而示例 4 是不正确的 - 即它不会产生任何结果,就像示例 1 一样。

为什么示例 2 仍然产生结果(即使它不是所需的结果),尽管它不使用 text.split()

>>> text = 'the quick brown fox jumps over the lazy dog'
  1. 形容词不匹配的情况:结果没有预期

    >>> adjectives = ['slow', 'crippled']
    >>> firstAdjective = next((word for word in adjectives if word in text), None)
    >>> firstAdjective
    >>>
    
  2. 与形容词中的第一个匹配但实际上在文本中的第二个匹配的大小写:

    >>> adjectives = ['slow', 'brown', 'quick', 'lazy']
    >>> firstAdjective = next((word for word in adjectives if word in text), None)
    >>> firstAdjective
    'brown'
    
  3. 与文本中可用的第一个匹配的大小写,这是想要的

    >>> firstAdjective = next((word for word in text.split() if word in adjectives), None)
    >>> firstAdjective
    'quick'
    
  4. .split() 被省略的情况。注意:这不起作用。

    >>> firstAdjective = next((word for word in text if word in adjectives), None)
    >>> firstAdjective
    >>>
    

这个例子来自我的问题Python: Expanding the scope of the iterator variable in the any() function的回答

【问题讨论】:

  • 为什么示例 4 有效?形容词中的字符串都不是单个字符长,因此没有单个字符可能是 in 它。示例 2 迭代 adjectives,例如'or' in 'hello world' 工作得很好。
  • @jonrsharpe 我猜他不知道迭代一个字符串会迭代它char wise 而不是 word wise。
  • 我建议你把它分解成更小的步骤,并使用传统的for循环,这样你就可以print每一步,而不是在“黑匣子”中进行 i> 并对最终结果感到惊讶。例如,我不清楚你为什么认为你会得到与示例 2 不同的结果;您要求adjectives 的第一场比赛,而不是adjectivesanythingtext 中的第一次出现。

标签: python list python-2.7 split


【解决方案1】:

迭代字符串 (text) 将迭代其字符,因此可以更明确地重写第 4 个循环:

firstAdjective = next((character for character in text if character in adjectives), None)

【讨论】:

    【解决方案2】:

    字符串是一个容器,所以in 仍然可以处理它。但是,它不会自然地分成单词,它会遍历字符。在示例 4 中,word 将连续获取每个字符的值。给它一个变量名word 并不意味着它是一个单词。

    在示例 2 中,您正在迭代列表 adjectives 而不是字符串,因此您得到了 word 的“预期”行为,它采用了一个单词的值。然后in 运算符检查word 是否是text 的子字符串,而不必使用split。请注意,text 不会拆分为单词。 'wn fo' in text 将返回 True

    【讨论】:

    • in 不是特定于迭代器的,而是containers
    猜你喜欢
    • 2018-06-14
    • 1970-01-01
    • 2020-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    相关资源
    最近更新 更多