6 个例子教你重构 Python 代码

本文介绍了几种Python代码优化方法,包括合并嵌套if条件、移除重复代码、使用yieldfrom提高效率、利用any()代替循环检查、使用简洁的列表和字典创建,以及将常量提前移出循环。这些技巧有助于提高代码的执行效率和可读性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 合并嵌套的 if 条件

合并之前:

if a:
    if b:
        return c

合并后:

if a and b:
    return c

2. 将重复的代码移到条件语句之外

if sold > DISCOUNT_AMOUNT:
    total = sold * DISCOUNT_PRICE
    label = f'Total: {total}'
else:
    total = sold * PRICE
    label = f'Total: {total}'
if sold > DISCOUNT_AMOUNT:
    total = sold * DISCOUNT_PRICE
else:
    total = sold * PRICE
label = f'Total: {total}'

3. 将内部循环中的yield替换为yield from

yield from使程序运行效率提高约 15%。

重构前:

def get_content(entry):
    for block in entry.get_blocks():
        yield block

重构后:

def get_content(entry):
    yield from entry.get_blocks()

4. 使用 any() 而不是用于循环

常见的模式是,我们需要查找是否集合中的一个或多个项符合某些条件。这可以通过 for 循环完成,例如:

found = False

for thing in things:
    if thing == other_thing:
        found = True
        break

更简洁的方法,是使用 Python 的 any() 和 all()内置函数,来清楚地显示代码的意图:

found = any(thing == other_thing for thing in things)

5. 用[]替换list()

创建列表的最简洁和 Pythonic 的方法是使用 []以获取更好的性能:

x = list()                # 不建议使用
x = []                    # 建议使用
x = ['first', 'second']   # 建议使用

同样的原因和性能表现,使用{}替代dict()。

6. 将重复执行的语句移出for/while循环

重构前:

for building in buildings:
    city = 'London'
    addresses.append(building.street_address, city)

重构后:

city = 'London'
for building in buildings:
    addresses.append(building.street_address, city)

参考链接:

https://sourcery.ai/blog/explaining-refactorings-1/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值