python循环代码优化笔记
2019-06-10 本文已影响0人
CapsulE_07
摘抄于腾讯技术知乎专栏:https://zhuanlan.zhihu.com/p/68128557
该篇仅做个人复习查询使用,对该内容感兴趣的朋友,请去原文链接阅读学习。
使用函数修饰被循环对象本身,可以改善循环体内的代码
itertools 里面有很多工具函数都可以用来改善循环
使用生成器函数可以轻松定义自己的修饰函数
循环内部,是一个极易发生“代码膨胀”的场地
请使用生成器函数将循环内不同职责的代码块解耦出来,获得更好的灵活性
##对于这种需要嵌套遍历多个对象的多层循环代码,我们可以使用函数来优化它。
##`product()`可以接收多个可迭代对象,然后根据它们的笛卡尔积不断生成结果。
from itertools import product
def find_twelve_v2(num_list1, num_list2, num_list3):
for num1, num2, num3 in product(num_list1, num_list2, num_list3):
if num1 + num2 + num3 == 12:
return num1, num2, num3
## 使用takewhile 替代break,为true则继续执行循环,false跳出
from itertools import takewhile
for user in takewhile(is_qualified, users):
# 进行处理 ... ...
#使用生成器函数解耦循环体
def gen_weekend_ts_ranges(days_ago, hour_start, hour_end):
"""生成特定时间区域时间戳"""
for days_delta in range(days_ago):
"""省略代码"""
yield ts_start, ts_end
def award_active_users_in_last_30days_v2():
"""发送奖励积分"""
for ts_start, ts_end in gen_weekend_ts_ranges(30, hour_start=20, hour_end=23):
for record in LoginRecord.filter_by_range(ts_start, ts_end):
send_awarding_points(record.user_id, 1000)