ITPub博客

首页 > 数据库 > 数据库开发技术 > 24个令人眼前一亮的Python技巧—提升你的代码水平和质量(二)

24个令人眼前一亮的Python技巧—提升你的代码水平和质量(二)

原创 数据库开发技术 作者:jackzhang 时间:2024-09-04 06:30:00 0 删除 编辑

前路漫漫,我爱Python。Hello,大家好!在上一篇文章中,我给大家分享了24个令人眼前一亮的Python技巧的前一半(24个令人眼前一亮的Python技巧—提升你的代码水平和质量(一))。今天,我们一起来看看剩余的12个技巧,助你提升代码质量和编码水平。

13. 使用布尔值检查来确定容器是否为空

# Bad
container: list = []
if len(container) == 0:
    print('No items in the container!')

# Better
container: list = []
if not container:
    print('No items in the container!')

14. any() 和 all() 简化多条件判断

any() 用于检查可迭代对象中是否至少有一个元素为真(True)。当需要检查多个条件中的任何一个是否成立时,可以使用 any() 来简化代码结构,避免繁琐的多重 or 语句。

# Bad
numbers: list[int] = [-5, -2, -3, -1, 4]
pos_flag: bool = False
for number in numbers:
    if number > 0:
        pos_flag = True
print(pos_flag)

# Better
numbers: list[int] = [-5, -2, -3, -1, 4]
print(any([number > 0 for number in numbers]))

all() 函数用于检查可迭代对象中的所有元素是否都为真(True)。当需要检查多个条件是否全部成立时,可以使用 all() 来避免多重 and 语句的使用。

# Bad
numbers: list[int] = [1, 2, 3, 4, 5]
pos_flag: bool = True
for number in numbers:
    if number > 0:
        pos_flag = False
        break
print(f"All numbers are positive: {pos_flag}")

# Better
numbers: list[int] = [-5, -2, -3, -1, 4]
pos_flag: bool = all([number > 0 for number in numbers])
print(f'All numbers are positive: {pos_flag}')

15. 字典中快速简单的键检查

如果你只想检测字典中是否存在某个键,则无需调用 .keys(),只需要在字典本身上使用关键字 in 即可。通过键迭代访问字典中的值也是如此。

# Bad
person_info: dict[str, list] = {
    'name': ['Jack', 'John', 'Alice'],
    'age': [20, 25, 35],
}
has_address: bool = True if 'address' in person_info.keys() else False
for key in person_info.keys():
    print(f'{key}: {person_info[key]}')

# Better
person_info: dict[str, list] = {
    'name': ['Jack', 'John', 'Alice'],
    'age': [20, 25, 35],
}
has_address: bool = True if 'address' in person_info else False
for key in person_info:
    print(f'{key}: {person_info[key]}')

16. 避免无用返回值的陷阱

不使用函数中有意义的返回值可能会妨碍代码的可理解性。设计具有返回值的函数非常重要,这些返回值可提供有用的信息,可以提高代码重用性和简洁性。

# Bad
def calculate_sum_of_numbers(numbers: list[int]) -> None:
    total: int = sum(numbers)
    print(f'Sum: {total}')

numbers: list[int] = [1, 2, 3, 4, 5]
calculate_sum_of_numbers(numbers)

# Better
def calculate_sum_of_numbers(numbers: list[int]) -> int:
    total: int = sum(numbers)
    return total

numbers: list[int] = [1, 2, 3, 4, 5]
result = calculate_sum_of_numbers(numbers)
print(f'Sum: {result}')

17. 使用比较链简化等价检查

在检查多个对象是否相等时,不要使用 and 表达式。比较链或许是一个不错的选择。

# Bad
x, y, z = 3, 3, 2
if x == y and y == z:
    print('x, y and z are equal')
else:
    print('x, y and z are not equal')

# Better
x, y, z = 3, 3, 2
if x == y == y == z:
    print('x, y and z are equal')
else:
    print('x, y and z are not equal')

18. 代码优化技巧——使用 operator 代替 lambda

不要编写函数(包括lambda)来包装内置运算符,而是使用 operator 模块。

# Bad
from functools import reduce

numbers: list[int] = [1, 2, 3]
print(reduce(lambda x, y: x * y, numbers))  # 6

# Better
from functools import reduce
from operator import mul

numbers: list[int] = [1, 2, 3]
print(reduce(mul, numbers))  # 6

19. os.path.join() 拼接路径的更好方法

# Bad
file_path: str = dir1 + dir2 + 'test1.txt'

# Better
import os.path
file_path: str = os.path.join(dir1, dir2 + 'test1.txt')

20. 不要在代码中硬编码敏感信息

对密码、安全代码或 API 密钥等敏感信息进行硬编码会带来巨大的安全风险,因为这会将这些数据暴露给潜在的攻击者。这种做法可能导致数据泄露或账户受损。

password = "iLOVEpython@666"

最好使用其他方法(如环境变量或配置文件)来存储敏感信息。环境变量提供了一种将数据保存在代码库之外的安全方法,而配置文件可以加密或存储在独立于代码库的安全位置。

21. 文件写入并非总是需要 open

当你只是想简单地向文件中写入内容时,相较于 open() 函数,通过 pathlib 模块的 write_text() 函数会更简洁:

# Bad
content: str = 'I love Python'
with open('test.txt', 'w') as f:
    f.write(content)

# Better
from pathlib import Path

content: str = 'I love Python'
Path('test.txt').write_text(content)

22. 异常处理——永远不要让 except 块为空

# Bad
try:
    file = open("test.txt","r")
    # other operations with the file
except:
    # error handling
    pass
finally:
    file.close()

# Better
try:
    file = open("test.txt","r")
    # other operations with the file
except FileNotFoundError:
    print("File not found")
except IOError as e:
    print(f'Error occurred while handling the file: {e}')
finally:
    file.close()

23. 访问字典值的更好方法—— get()

在访问字典中的值时,使用 get() 方法可能比使用标准索引更安全、更简洁。该方法允许你在找不到键时提供默认值,从而避免潜在的 KeyError 异常。

# Bad
person_info: dict[str, str | int] = {'name': 'Jack', 'age': 25}
print(person_info['city'])  # KeyError: 'city'

# Better
person_info: dict[str, str | int] = {'name': 'Jack', 'age': 25}
print(person_info.get('city'))  # None
print(person_info.get('city', 'Unknown key'))   # Unknown key

24. 使用 match...case 语句实现更好的条件控制

# Bad
def describe_type(obj) -> str:
    if isinstance(obj, str):
        return "It's a string"
    elif isinstance(obj, list):
        return "It's a list"
    else:
        return "It's something else"

# Better
def describe_type(obj) -> str:
    match obj:
        case str():
            return "It's a string"
        case list():
            return "It's a list"
        case _:
            return "It's something else"

最后的话

OK,关于24个令人眼前一亮的Python技巧,就分享到这啦!感谢你的阅读,希望对你有所帮助!


推荐阅读👇👇👇

24个令人眼前一亮的Python技巧—提升你的代码水平和质量(一)

10个令人相见恨晚的Python高效编程技巧!

Python必知必会:令人相见恨晚的10个Python类技巧(二)

Python必知必会:令人相见恨晚的10个Python类技巧(一)

5个良好的Python编程习惯,助你成为Python高手!

- END -

🌟 如果你喜欢这篇文章并且愿意支持我的话,你可以: 🌟

  • 👍👍👍 点赞文章
  • ⤴️⤴️⤴️ 转发文章
  • ⚛️⚛️⚛️ 点击在看
  • 🧑‍🤝‍🧑🧑‍🤝‍🧑🧑‍🤝‍🧑 让文章被推荐给更多人,找到更多志同道合的伙伴
  • 👏👏👏 欢迎给我留言

关注我,第一时间接收更多关于Python、数据分析和机器学习的深入分析和最新趋势。我们一起探索数据的力量,解锁AI的潜能。你的每一次互动都是对我的极大鼓励,也是我们共同成长的动力!

👇👇👇 关注并开启星标提醒,让知识与技能的火花不断在你的职业道路上燃烧吧!

原文作者:数据派探险家;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2017-12-19

  • 博文量
    119
  • 访问量
    55951