我很难理解为什么一个相同的条件语句在一个包含多个iterable的列表中的位置会影响结果。在
>>> 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上提出/回答了此问题,请提前致歉。在
你所做的与:
由于
b
和g
已经定义并填充了上一次运行的值,因此会发生以下情况:Jim
。m
在{(Jim, Bonnie)
(Jim, Buffy)
Jeff
f
在Buffy
中?是-跳过内循环。在如果您首先在一个新的Python shell中运行它,它将引发一个
^{pr2}$Exception
:相关问题 更多 >
编程相关推荐