gpt4 book ai didi

python - 在具有多个可迭代对象的 python 列表理解中定位条件语句

转载 作者:行者123 更新时间:2023-11-28 16:47:14 26 4
gpt4 key购买 nike

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

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

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

  • 第一个外循环 Jim
    • mBuffy 中?否 - 运行内循环:
    • 附加 (吉姆,邦妮)
    • 附加 (吉姆、巴菲)
  • 第二个外循环 Jeff
    • fBuffy 中?是 - 跳过内循环。

如果您首先在 Python shell 中运行它,它会引发异常:

>>> # 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 - 在具有多个可迭代对象的 python 列表理解中定位条件语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12549717/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com