本來使用循環:app
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}')
使用生成器能夠更高效的傳輸ide
def gen_num(): for i in range(10): print(f'生成數據:{i}') yield i nums = gen_num() for num in nums: print(f'打印數據:{num}')
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))