![](/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.