Python:分配“通过”迭代器 [英] Python: Assigning "through" an iterator

查看:106
本文介绍了Python:分配“通过”迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可变序列的迭代器,例如

I have an iterator over a mutable sequence, e.g.

foo = [1,2,3,4,5]
for bar in foo:

有没有办法写入foo中的元素使用迭代器中包含的引用?天真的任务:

Is there a way to write to the elements in foo by using the reference which is contained in the iterator? The naive assignment:

   bar = 42

当然不起作用。是否可以使用幕后引用迭代器中的序列元素?

does not work of course. Is it possible to use the "behind the curtain" reference to the sequence element which is in the iterator ?

PS:使用索引的简单解决方案

PS: The simple solution with using an index

for i in range(len(a)):
   a[i] = 42

对我的情况不起作用,因为我无法公开容器名称。

will not work for my case, as I can't expose the container name.

推荐答案

据我了解,您的用例是这样的:

From my understanding, your use case is something like this:

class Z:
    def __init__(self):
        self.a, self.b, self.c = 1,2,3

    def it(self):
        for x in self.a, self.b, self.c:
            yield x

z = Z()
for x in z.it():
    if x == 1:
       x = 42 # z.a should be 42? - doesn't work!

这在python中是不可能的 - 没有指针或引用数据类型。你可以通过产生一个setter函数而不是(或同时)来解决这个问题:

This isn't possible in python - there's no "pointer" or "reference" data type. You can work around this by yielding a setter function instead of (or along with) the value:

class Z:
    def __init__(self):
        self.a, self.b, self.c = 1,2,3

    def it(self):
        for x in 'abc':
            yield getattr(self, x), lambda y: setattr(self, x, y)

z = Z()
for x, setter in z.it():
    if x == 1:
       setter(42) # works!

这篇关于Python:分配“通过”迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆