[英]python - getting specific generator data from the generator
let's start with the code让我们从代码开始
class MyClass:
def __init__(self):
self.elemplusone = None
self.elemplustwo = None
self.data = self.generate_data()
def generate_data(self):
for elem in range(10):
yield elem+1, elem+2
I need to get the first and the second element of generator.我需要获取生成器的第一个和第二个元素。 Right now, I'm calling it outside the class after creating an object:
现在,我在创建 object 之后在 class 之外调用它:
a_generator = MyClass()
c = next(a_generator.data)
elemplusone = c[0]
elemplustwo = c[1]
but I need them to be specified (as separate generators) in the class and I can't create two generator methods.但我需要在 class 中指定它们(作为单独的生成器),我无法创建两个生成器方法。
Thanks谢谢
I also don't quite understand what you mean exactly.我也不太明白你到底是什么意思。 But does this help you?
但这对你有帮助吗?
class MyClass:
def __init__(self):
self.data = self.generate_data()
self.update_elements()
def update_elements(self):
self.elemplusone, self.elemplustwo = [x for x in next(self.data)]
def generate_data(self):
for elem in range(10):
print("Yielded")
yield elem + 1, elem + 2
a_generator = MyClass()
a_generator.elemplusone
is 1 and a_generator.elemplustwo
is 2. a_generator.elemplusone
为 1, a_generator.elemplustwo
为 2。
Now you could call a_generator.update_elements()
to yield your elements again and continue in your generator.现在您可以调用
a_generator.update_elements()
再次生成您的元素并在您的生成器中继续。 Please let me know if this helps you.如果这对您有帮助,请告诉我。 Good luck!
祝你好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.