我希望跟踪某些值(比如计数,统计数据),而生成器会产生其他值。我目前的方法是将可变对象传递给生成器。用"返回"返回这些值。似乎不起作用。如果还有其他办法,我很好奇。
在下面的示例中,生成器从当前脚本生成代码行,字典跟踪器也跟踪计数:
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']}")
答案 0 :(得分:1)
如何产生由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)
或者您可以使用可迭代类(使用__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)