Python yield: return 或访问在生成器中计算的其他值
Python yield: return or access other values computed within a generator
我想在生成器生成其他值的同时跟踪某些值(比如计数、统计信息)。我目前的方法是将一个可变对象传递给生成器。使用 "return" 返回这些值似乎不起作用。我很好奇是否还有其他方法可以做到这一点。
在以下示例中,生成器从当前脚本生成代码行,字典跟踪器也跟踪计数:
import sys
def gen_lines_of_code(tracker):
loc = 0
with open(sys.argv[0]) as fp:
for line in fp:
if len(line.strip()) > 0:
loc += 1
yield line
tracker["count"] = loc
# Dictionary to keep track of count of lines of code
track = {"count": 0}
g = gen_lines_of_code(track)
for v in g:
print(v, end="")
print(f"\n\tLines of code in {sys.argv[0]}: {track['count']}")
生成由 line 和 loc 组成的元组怎么样?
import io
def gen_lines_of_code(file):
loc = 0
for line in file:
if line.strip():
loc += 1
yield line, loc
file = io.StringIO("""
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco
laboris nisi ut aliquip ex ea commodo consequat.
""")
g = gen_lines_of_code(file)
for v, loc in g:
print(v, end='')
try:
print("\n\tLines of code:", loc)
except NameError:
loc = 0
print("\n\tLines of code:", loc)
或者您可以使用可迭代的 class(使用 __iter__
方法):
class GenLinesOfCode:
def __init__(self, file):
self.file = file
self.loc = 0
def __iter__(self):
for line in self.file:
if line.strip():
self.loc += 1
yield line
g = GenLinesOfCode(file)
for v in g:
print(v, end='')
print("\n\tLines of code:", g.loc)
我想在生成器生成其他值的同时跟踪某些值(比如计数、统计信息)。我目前的方法是将一个可变对象传递给生成器。使用 "return" 返回这些值似乎不起作用。我很好奇是否还有其他方法可以做到这一点。
在以下示例中,生成器从当前脚本生成代码行,字典跟踪器也跟踪计数:
import sys
def gen_lines_of_code(tracker):
loc = 0
with open(sys.argv[0]) as fp:
for line in fp:
if len(line.strip()) > 0:
loc += 1
yield line
tracker["count"] = loc
# Dictionary to keep track of count of lines of code
track = {"count": 0}
g = gen_lines_of_code(track)
for v in g:
print(v, end="")
print(f"\n\tLines of code in {sys.argv[0]}: {track['count']}")
生成由 line 和 loc 组成的元组怎么样?
import io
def gen_lines_of_code(file):
loc = 0
for line in file:
if line.strip():
loc += 1
yield line, loc
file = io.StringIO("""
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco
laboris nisi ut aliquip ex ea commodo consequat.
""")
g = gen_lines_of_code(file)
for v, loc in g:
print(v, end='')
try:
print("\n\tLines of code:", loc)
except NameError:
loc = 0
print("\n\tLines of code:", loc)
或者您可以使用可迭代的 class(使用 __iter__
方法):
class GenLinesOfCode:
def __init__(self, file):
self.file = file
self.loc = 0
def __iter__(self):
for line in self.file:
if line.strip():
self.loc += 1
yield line
g = GenLinesOfCode(file)
for v in g:
print(v, end='')
print("\n\tLines of code:", g.loc)