我很难理解为什么在多个迭代的列表理解中放置相同的条件语句会影响结果。
>>> 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 上询问/回答了这个问题,请提前道歉。