【发布时间】:2016-07-20 12:39:06
【问题描述】:
为什么下面的示例 3(使用 text.split())会产生正确的结果,而示例 4 是不正确的 - 即它不会产生任何结果,就像示例 1 一样。
为什么示例 2 仍然产生结果(即使它不是所需的结果),尽管它不使用 text.split()?
>>> text = 'the quick brown fox jumps over the lazy dog'
-
形容词不匹配的情况:结果没有预期
>>> adjectives = ['slow', 'crippled'] >>> firstAdjective = next((word for word in adjectives if word in text), None) >>> firstAdjective >>> -
与形容词中的第一个匹配但实际上在文本中的第二个匹配的大小写:
>>> adjectives = ['slow', 'brown', 'quick', 'lazy'] >>> firstAdjective = next((word for word in adjectives if word in text), None) >>> firstAdjective 'brown' -
与文本中可用的第一个匹配的大小写,这是想要的
>>> firstAdjective = next((word for word in text.split() if word in adjectives), None) >>> firstAdjective 'quick' -
.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 我猜他不知道迭代一个字符串会迭代它
charwise 而不是 word wise。 -
我建议你把它分解成更小的步骤,并使用传统的
for循环,这样你就可以print每一步,而不是在“黑匣子”中进行 i> 并对最终结果感到惊讶。例如,我不清楚你为什么认为你会得到与示例 2 不同的结果;您要求adjectives的第一场比赛,而不是adjectives的anything 的text中的第一次出现。
标签: python list python-2.7 split