我很难理解为什么在列表中理解多个迭代的相同条件语句的位置会影响结果。
>>> 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上询问/回答了这个问题,请提前道歉。
答案 0 :(得分:3)
你所做的与以下相同:
>>> boys = 'Jim','Jeff'
>>> girls = 'Bonnie', 'Buffy'
>>>
>>> out = []
>>> for b in boys:
... for g in girls:
... out.append((b,g))
...
>>> out
[('Jim', 'Bonnie'), ('Jim', 'Buffy'), ('Jeff', 'Bonnie'), ('Jeff', 'Buffy')]
>>>
>>> out = []
>>> for b in boys:
... for g in girls:
... if b[-1] not in g:
... out.append((b,g))
...
>>> out
[('Jim', 'Bonnie'), ('Jim', 'Buffy'), ('Jeff', 'Bonnie')]
>>>
>>> b
'Jeff'
>>> g
'Buffy'
>>> out = []
>>> for b in boys:
... if b[-1] not in g:
... for g in girls:
... out.append((b,g))
...
>>> out
[('Jim', 'Bonnie'), ('Jim', 'Buffy')]
由于b
和g
已经定义并填充了上次运行的值,因此会发生以下情况:
Jim
。
m
中Buffy
?不 - 运行内循环:(Jim, Bonnie)
(Jim, Buffy)
Jeff
f
中Buffy
?是的 - 跳过内循环。 如果你先在 new Python shell中运行它,那么它会引发Exception
:
>>> # b = g = None
>>> boys = 'Jim','Jeff'
>>> girls = 'Bonnie', 'Buffy'
>>>
>>> [(b,g) for b in boys if b[-1] not in g for g in girls]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
UnboundLocalError: local variable 'g' referenced before assignment