yield用法
原本使用循环:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def gen_num(): nums = [] for i in range(10): print(f'生成数据:{i}') nums.append(i) return nums nums = gen_num() for num in nums: print(f'打印数据:{num}')
使用生成器可以更高效的传输
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def gen_num(): for i in range(10): print(f'生成数据:{i}') yield i nums = gen_num() for num in nums: print(f'打印数据:{num}')
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
CHINESE_NUM_DICT = { '一': '1', '二': '2', '三': '3', '四': '4', '五': '5', '六': '6', '七': '7', '八': '8', '九': '9' } def get_data(): datas = (41234213424, '一九八八七二六三', 8394520342, '七二三六二九六六', '敏感信息', 80913408120934, '敏感信息', '敏感信息', 95352345345, '三三七四六', 999993232, 234234234, '三六八八七七', '敏感信息') for data in datas: yield data def remove_sensitive_data(datas): for data in datas: if data == "敏感信息": continue yield data def tranfer_chinese_num(datas): for data in datas: try: num = int(data) except ValueError: num = int(''.join(CHINESE_NUM_DICT[x] for x in data)) yield num def save_data(number_list): data_list = [] for num in number_list: data_list.append(num) return data_list raw_data = get_data() safe_data = remove_sensitive_data(raw_data) number_list = tranfer_chinese_num(safe_data) print(save_data(number_list))