![](/img/trans.png)
[英]Pythonic way of determining if the current element is the first or last element of a generator?
[英]Most pythonic way to get variable based on last element in generator?
我有以下代码:
class MyClass:
def __init__(self):
self.some_variable = None
def func1(self):
i = 1
while i < 10:
yield i * i
self.some_variable = len(str((i * i)))
i += 1
def func2(self):
*_, last = my_class.func1()
print(self.some_variable)
my_class = MyClass()
my_class.func2()
如您所见,some_variable 是生成器中最后一个元素的长度。 基本上,我想知道,这是获取此变量的最 pythonic 方式吗? 如果不是,应该怎么做? 我只是想知道是否应该这样做,或者是否有更好的方法。
可能最简单的代码就是简单地使用for
循环来使用生成器,在循环体中什么都不做。 循环变量将在循环结束后拥有来自生成器的最后一个值,这正是您想要的。
for x in some_generator():
pass
print(x) # print the last value yielded by the generator
这可能比其他选项更有效一些,因为它会丢弃最后一个之前的所有值,而不是将它们存储在列表或其他一些数据结构中。
我认为一种 pythonic 方式是产生元素和长度:
def func1():
i = 1
while i < 10:
yield i * i, len(str((i * i)))
i += 1
def func2():
*_, (_, last_len) = func1()
print(last_len)
func2()
甚至将派生值的计算提取到另一个 function 并在使用生成器后调用它:
def func1():
i = 1
while i < 10:
yield i * i
i += 1
def func2(i):
return len(str(i))
def func3():
*_, last = func1()
print(func2(last))
func3()
我认为您已经过度简化了您的示例,以至于无法找到最适合您的实际用例的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.