2017-10-02 14 views
2

ジェネレータが何か他のものをもたらす間、特定の値(カウント、統計など)を追跡したいと思います。私の現在のアプローチは、変更可能なオブジェクトをジェネレータに渡すことです。これらの値を「戻る」で返すことは機能していないようです。他の方法があれば私は興味がありました。次の例ではPython yield:ジェネレータ内で計算された他の値を返すか、アクセスします。

、発電機は、現在のスクリプトからコードの行を生成し、辞書トラッカーはまた、カウントを追跡します:

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']}") 

答えて

1

どのラインと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) 
+0

によるライブラリーから来ている消費者にもたらしたことができるかの制限があります。 – yang5

+1

iterableクラスの2番目の変種は機能しますか?イテレータでなければならない場合は、 '__next__'メソッドを与えることもできます。 – skrx

関連する問題