<jupyter_start><jupyter_text>yield可以让一个函数变成“生成器”（generator），每次调用这个函数时通过yield返回一个值，下次调用这个函数时会从yield的下一条语句开始执行，直到遇到yield返回一个值或者return语句终止函数执行。因此，yield配合循环或者迭代过程可以构造简洁直观的代码，比如斐波那契数列可以这样写：<jupyter_code>def fabonacci(num_items):
    a,b,n = 0,1,0
    while(n < num_items):
        yield b
        a,b,n = b,(a+b),n+1
    
for n in fabonacci(5):
    print(n)<jupyter_output>1
1
2
3
5<jupyter_text>又比如，在处理excel或者csv文件时，可以使用yield来获取指定的内容（感谢[zzliu](https://github.com/zz2liu)的指点，参见[A股年报数据提取小工具](https://subaochen.github.io/python/2019/07/11/stock-report-data-miner/)的评论内容）：<jupyter_code>codes = ['603730', '603757']
years = ['2018-12-31', '2017-12-31']
def each_record(codes, years, row='营业收入(万元)'):
    for code in codes:
        filename = f'data/lrb_{code}.csv'
        df = pd.read_csv(filename, index_col=0)
        x = df.loc[row, years]
        yield [code] + list(x)
summary = pd.DataFrame.from_records(each_record(codes, years), columns=['code'] + years)
summary.to_csv('tmp.csv', index=False)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.15933528836754643, 'fraction_numerical': 0.0469208211143695, 'mean_word_length': 5.440251572327044, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 8, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '178425', 'license': 'MIT', 'n_tokens_mistral': 550, 'n_tokens_neox': 552, 'n_words': 50, 'path': 'resources/posts/yield-python.ipynb', 'repo_name': 'subaochen/subaochen.github.io', 'size': '1023'}