编程语言
首页 > 编程语言> > 带多个可迭代项的python列表理解中条件语句的位置

带多个可迭代项的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上提出/回答了此问题,请提前道歉.

解决方法:

您所做的与以下操作相同:

>>> 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,并使用上次运行的值进行填充,因此会发生以下情况:

>第一个外循环吉姆.

>米在布菲?否-运行内部循环:
>追加(吉姆,邦妮)
>追加(吉姆,布菲)

>第二个外循环杰夫

> Buffy中的f?是的-跳过内循环.

如果您首先在新的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

标签:python,list-comprehension
来源: https://codeday.me/bug/20191127/2075471.html