简体   繁体   English

基于生成器中最后一个元素获取变量的大多数 pythonic 方法?

[英]Most pythonic way to get variable based on last element in generator?

I have the following code:我有以下代码:

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()

As you can see, some_variable is the length of the last element in the generator.如您所见,some_variable 是生成器中最后一个元素的长度。 Basically, I was wondering, is this the most pythonic way of getting this variable?基本上,我想知道,这是获取此变量的最 pythonic 方式吗? If not, how should this be done?如果不是,应该怎么做? I'm just wondering if this is how it should be done or if there's a better way of doing this.我只是想知道是否应该这样做,或者是否有更好的方法。

Probably the simplest code is to simply use a for loop to consume the generator, doing nothing in the loop body.可能最简单的代码就是简单地使用for循环来使用生成器,在循环体中什么都不做。 The loop variable will have the last value from the generator after the loop ends, which is exactly what you want.循环变量将在循环结束后拥有来自生成器的最后一个值,这正是您想要的。

for x in some_generator():
    pass

print(x) # print the last value yielded by the generator

This may be a little more efficient than other options because it discards all the values before the last one, rather than storing them in a list or some other data structure.这可能比其他选项更有效一些,因为它会丢弃最后一个之前的所有值,而不是将它们存储在列表或其他一些数据结构中。

I think that one pythonic way would be to yield both the element and the length:我认为一种 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()

or even to extract the calculation of the derived value to another function and call it after consuming the generator:甚至将派生值的计算提取到另一个 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()

I think that you have simplified your example too much to be able to find the solution that fits your real use case the best.我认为您已经过度简化了您的示例,以至于无法找到最适合您的实际用例的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM