때때로 반복이 그렇게 나쁘지 않습니다! 이 같은
어쨌든 당신이 시도 할 수있는 무언가 :
#!/usr/bin/env python
# script.py
def process_file(filename, func1, func2):
with open(filename) as f:
for line in f:
if '1' in line:
func1(line)
if '2' in line:
func2(line)
def main():
counters = {1: 0, 2: 0}
def func1(line):
# TODO Add some logic based on line value here
counters[1] += 1
def func2(line):
counters[2] += 1
process_file('table.csv', func1, func2)
return counters
if __name__ == '__main__':
print(main())
그리고 당신은 파일이있는 경우 : 스크립트를
$ cat table.csv
1 just one
1 2 one and two
1
1
0
0
2
2 1
1 0 2
0
을 그리고 실행
python script.py
당신은 얻을 것이다 다음 출력 :
{1: 6, 2: 3}
또한 당신은 당신의 if
문장의 조건을 반영 할 수
def process_file(filename, func1, func2, predicate1, predicate2):
with open(filename) as f:
for line in f:
if predicate1(line):
func1(line)
if predicate2(line):
func2(line)
def predicate1(line):
return 'REW' in line or 'LOSE' in line
좋은 기능 이름을 선택하는 것을 잊지 마세요!
* 리팩토링이 필요하다고 생각합니다. 그리고 나는 발전기를 만들 필요가 있다고 생각합니다. * 당신은 정확히 무엇입니까? –
반복 코드를 단순히 함수로 만들면 함수를 대신 호출 할 수 있습니다. ??? – coder
리팩터링하는 방법은 괄호로 묶은 코드가 할 수있는 것에 따라 달라집니다. ('return','continue','break' 또는'yield'를 사용합니까?) – chepner