3

我很难理解为什么在多个迭代的列表理解中放置相同的条件语句会影响结果。

>>> 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 上询问/回答了这个问题,请提前道歉。

4

1 回答 1

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')]

由于bg已经定义并填充了上次运行的值,因此会发生以下情况:

  • 第一个外循环Jim
    • mBuffy?否 - 运行内部循环:
    • 附加(Jim, Bonnie)
    • 附加(Jim, Buffy)
  • 第二外环Jeff
    • fBuffy?是的 - 跳过内循环。

如果您首先在的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
于 2012-09-23T04:42:58.760 回答