3
我很难理解为什么定义一个相同的条件语句在多个迭代列表中的理解会影响结果。条件语句在Python列表中的理解与多个迭代的定位
>>> boys = 'Jim','Jeff'
>>> girls = 'Bonnie', 'Buffy'
# This generates four tuples as expected
>>> [(b,g) for b in boys for g in girls]
[('Jim', 'Bonnie'), ('Jim', 'Buffy'), ('Jeff', 'Bonnie'), ('Jeff', 'Buffy')]
# If the conditional "if b[-1] not in g" is at the end of the LC we get 3
>>> [(b,g) for b in boys for g in girls if b[-1] not in g]
[('Jim', 'Bonnie'), ('Jim', 'Buffy'), ('Jeff', 'Bonnie')]
# If the conditional is after the first sequence, we only get two results
>>> [(b,g) for b in boys if b[-1] not in g for g in girls]
[('Jim', 'Bonnie'), ('Jim', 'Buffy')]
如果其他人已经在StackOverflow上提出/回答了此问题,请事先道歉。
我怀疑问题可能与优先级。 Parens解决歧义并恢复预期行为吗? –
@BrianCain:这不是优先,它是LC的结构。 “if”放置在外部循环中,而不是第三个变体中的内部循环。 –