输出:
[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.
更多推荐
发布评论