发电机很奇怪(The generator works strange)

编程入门 行业动态 更新时间:2024-10-27 05:28:34
发电机很奇怪(The generator works strange) a = [1, 2, 3] b = (c for c in a if c in a) a = [2, 3, 4] print(list(b)) def d(expr): for c in expr: if c in expr: yield c a1 = [1,2,3] t = d(a1) a1 = [2,3,4] print(list(t))

输出:

[2, 3] [1, 2, 3]

问题:1)在第一个变体中,循环保留列表的旧值([1,2,3]),但条件表达式采用新的列表a([2,3,4])。 2)我自己的生成器如何给出除生成表达之外的其他结果?

例如,我替换了第一个例子的真实列表,我希望这将更清楚我的第一个问题。

a = [1, 2, 3] b = (c for c in [1,2,3] if c in [2, 3, 4]) a = [2, 3, 4] print(list(b))

输出:

[2,3]a = [1, 2, 3] b = (c for c in a if c in a) a = [2, 3, 4] print(list(b)) def d(expr): for c in expr: if c in expr: yield c a1 = [1,2,3] t = d(a1) a1 = [2,3,4] print(list(t))

output:

[2, 3] [1, 2, 3]

question: 1) in the first variant, the cycle retains the old value of the list ([1,2,3]), but the conditional expression takes a new list a([2,3,4]). 2) how my own generator give me other result than generative expression?

For example, I replaced a on the real lists of the first example, I hope this will be more clear my first question.

a = [1, 2, 3] b = (c for c in [1,2,3] if c in [2, 3, 4]) a = [2, 3, 4] print(list(b))

Output:

[2,3]

最满意答案

根据PEP 289 ,我们可以按如下方式重写您的生成器表达式:

# b = (c for c in a if c in a) def __gen(expr): for c in expr: if c in a: yield c b = __gen(iter(a))

这里,立即捕获用于for循环的[1, 2, 3]的引用(当你创建b ),但是检查中的if c in a使用等于[2, 3, 4]的新全局a [2, 3, 4] 。

另一方面,当您编写生成器函数时, a1传递给函数并存储以供稍后在for和if x in y表达式。 分配a1 = [2, 3, 4]无效。

要使函数与生成器表达式执行相同的操作,您需要做的就是将if c in expr替换if c in a1 。

As per PEP 289, we can rewrite your generator expression as follows:

# b = (c for c in a if c in a) def __gen(expr): for c in expr: if c in a: yield c b = __gen(iter(a))

Here, a reference to [1, 2, 3] for use in the for loop is captured immediately (when you create b), but the if c in a check uses the new global a which is equal to [2, 3, 4].

On the other hand, when you write a generator function, a1 is passed to the function and stored for later use in both for and if x in y expressions. Assigning a1 = [2, 3, 4] has no effect.

To make the function do the same thing as the generator expression, all you need to do is replace if c in expr with if c in a1.

更多推荐

本文发布于:2023-08-03 13:40:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1391323.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:很奇怪   发电机   generator   works   strange

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!