8招让Python代码更优雅

公众号:尤而小屋
编辑:Peter
作者:Peter

大家好,我是Peter~

大家知道《Python之禅》吗?

Python禅(The Zen of Python)是Python编程语言的设计哲学,它包含了一组简洁而富有智慧的格言,旨在指导Python开发者编写高质量的代码。这些格言可以通过在Python解释器中输入import this来查看。以下是Python禅的内容:

  1. 优美胜于丑陋(Beautiful is better than ugly.)
  2. 显式胜于隐式(Explicit is better than implicit.)
  3. 简单胜于复杂(Simple is better than complex.)
  4. 复杂胜于混乱(Complex is better than complicated.)
  5. 可读性计数(Readability counts.)
  6. 即使假借特例的实用性之名,也不可违背这些规则(Special cases aren’t special enough to break the rules.)
  7. 尽管实用性胜过纯洁性(Although practicality beats purity.)
  8. 错误不应该用沉默来掩盖(Errors should never pass silently.)
  9. 除非明确地忽略错误(Unless explicitly silenced.)
  10. 应该有一种且最好只有一种显而易见的方法来做到这一点(There should be one-- and preferably only one --obvious way to do it.)
  11. 虽然这种方式一开始可能并不明显(Although that way may not be obvious at first unless you’re Dutch.)
  12. 现在总比没有好(Now is better than never.)
  13. 虽然从来没有比现在更好(Although never is often better than right now.)
  14. 如果执行很难被解释,那将是一个很糟的想法(If the implementation is hard to explain, it’s a bad idea.)
  15. 如果执行很容易解释,这会是一个好点子(If the implementation is easy to explain, it may be a good idea.)
  16. 命名空间是一种很好的事物(Namespaces are one honking great idea – let’s do more of those!)

import this

import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

下面介绍7种方式叫你编写更简洁、高效的python代码。

三元条件运算符,替代if-else结构体:真简洁

if-else结构体在编程中是很常见的,当然也非常的通俗易懂,它是一种基础的控制流语句,用于根据条件的真假来控制程序的执行路径。在编程语言中,if-else结构体扮演着至关重要的角色,它允许开发者根据特定条件是否满足来选择执行不同的代码块。

比如下面的例子:

a = 10
b = 15

# 如果a小于b,则a是小值min_value;否则b是min_value
if a < b:
    min_value = a
else:
    min_value = b
    
min_value  # 结果是a

10

只用一行代码解决:使用三元运算符

min_value = a if a < b else b

min_value   # 结果还是a

10

巧用itertools.product函数:真实用

现在有一个3层的for循环代码:

list1 = [1,2,3]
list2 = [4,5,6]
list3 = [7,8,9]

for i in list1:
    for j in list2:
        for k in list3:
            if i%3==0 and j%3==0 and k%3==0:   
                print(i,j,k) 

3 6 9

现在使用product函数来完成上面的功能。首先我们看看product函数是什么。

from itertools import product

# 定义两个列表
l1 = ["a","b"]
l2 = [1, 2]

result = product(l1,l2)  # 可迭代对象
result

<itertools.product at 0x290f181f840>

# 遍历结果
for item in result: 
    print(item)
('a', 1)
('a', 2)
('b', 1)
('b', 2) 

从结果中可以看到:生成的是给定两个列表中元素的一一组合,这就是笛卡尔积

# 还是上面的3个列表
list1 = [1,2,3]
list2 = [4,5,6]
list3 = [7,8,9]

for i,j,k in product(list1, list2, list3):  # 迭代笛卡尔积
    if i%3==0 and j%3==0 and k%3==0:
        print(i,j,k)

3 6 9

Python列表推导式:真灵活

Python列表推导式(List Comprehension)是一种从其他列表创建新列表的方式,可以使用简洁的语法快速生成满足特定条件的列表。这种语法结构不仅让代码更简洁易读,而且能有效提高代码执行效率。

# 每个元素的平方

squares = [x**2 for x in range(11)]
squares

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

ages = [22,24,27,28]

# 让每个年龄加3
[age + 3 for age in ages]

[25, 27, 30, 31]

如果使用for循环来实现:

ages_add3 = []

for age in ages:
    ages_add3.append(age+3)
    
ages_add3

[25, 27, 30, 31]

再看另一个例子:

names = ["JACK","LINDA","mike","joHn"]

# 让每个名字变成:首字母大写,其他字母小写
[name.title() for name in names]

[‘Jack’, ‘Linda’, ‘Mike’, ‘John’]

海象运算符:真可爱

从python3.8开始,python中出现了海象运算符:=,用于赋值表达式。这个符号:=来源于海象的眼睛和獠牙。如何理解这个符号?

name = "Peter"
print(name)

Peter

可以将上面的第一行语句直接放到print函数中吗?答案是不能

print(name="Peter")
    ---------------------------------------------------------------------------

    TypeError                                 Traceback (most recent call last)

    Cell In[13], line 1
    ----> 1 print(name="Peter")
    

    TypeError: 'name' is an invalid keyword argument for print()

海象运算符能够实现上面的需求:

print(name:="Peter")  # 漂亮!

Peter

f-strings格式化字符串:真优雅

Python中的f-strings格式化技巧包括文本对齐、日期和时间格式、带分隔符的数字等。

f-string,即格式化字符串字面量(formatted string literals),是Python 3.6引入的一种新的字符串格式化方法。这种格式化技巧不仅提高了代码的可读性和简洁性,还提升了执行效率

# 案例1:显示具体信息

name = "张三"
age = 20
print(f"{name}的年龄是 {age} 岁")

张三的年龄是 20 岁

# 案例2:指定显示小数位

pi = 3.1415926
print(f"圆周率的值是:{pi:.2f}")  # 保留2位小数

圆周率的值是:3.14

# 案例3:格式化日期时间

import datetime
today = datetime.date.today()
print(f"今天是{today:%Y年%m月%d日}")

今天是2024年06月06日

# 案例4:文本宽度和对齐

name = "李四"
age = 25
print(f"{name:<10}{age:>5}")

李四 25

# 案例5:嵌套表达式

a = 5
b = 3
print(f"{a}乘以{b}等于{a * b}")  # 内部实施计算a*b

5乘以3等于15

# 案例6:内部使用字典

person = {"name": "Peter", "age": 30}
print(f"{person['name']} is {person['age']} years old.")

Peter is 30 years old.

# 案例7:格式化金额数据

N = 1000000000  
print(f'Money is ${N:,d}')

Money is $1,000,000,000

## Lambda匿名函数:真神秘

Python的lambda函数是一种匿名函数,主要用于创建简单的、单行的、临时使用的函数对象。lambda函数的定义包括三个基本部分:

  • 关键字lambda
  • 参数列表
  • 表达式。

它的基本语法结构为:lambda [arg1 [,arg2,.....argn]]:expression。其中,arg1argn是可选的参数列表,expression是一个基于这些参数的表达式,它的计算结果将作为lambda函数的返回值

# 计算两个数的和

add = lambda x, y: x + y  # 定义匿名函数

result = add(3, 5)  # 给匿名函数传入参数
result

8

# 列表元素求和

sum_list = lambda lst: sum(lst)
result = sum_list([1, 2, 3, 4, 5])
print(result)

15

title_case = lambda s: s.title()  # 定义匿名函数:单词的首字母大写,其他小写

result = title_case("hello world")
print(result)

Hello World

Python高阶函数:真好用

1、map函数是一个内置的高阶函数,用于对一个或多个可迭代对象(如列表、元组等)中的每一个元素应用指定的函数,并返回一个新的迭代器。

names = ["JACK","LINDA","mike","joHn"]

# 需求:让每个名字变成:首字母大写,其他字母小写
names = map(str.title,names)  # 生成的可迭代对象
list(names)

[‘Jack’, ‘Linda’, ‘Mike’, ‘John’]

def add_three(x):  # 自定义函数
    return x+3

ages = [22,24,27,28]

# 让每个年龄加3
ages = map(add_three, ages)  # 传入自定义的函数;然后对ages中每个元素执行自定义函数的操作+3
list(ages)

[25, 27, 30, 31]

2、另一个高阶函数reduce,它标示的是对一个可迭代对象实施累积(累乘、累加等)的操作:

from functools import reduce  # 导入模块
import operator

lst = [1,2,3,4,5]
reduce(operator.mul, lst)  # 累乘

120

lst = [1,2,3,4,5]
reduce(operator.add, lst)  # 累加

15

reduce函数和匿名函数的结合:

lst = ["My","name", "is", "Peter"]

reduce(lambda x,y: str(x) + " " +  str(y), lst)

‘My name is Peter’

联合运算符|合并字典:真高效

从python3.9开始出现了合并字典的高效方法,使用|符号:

names = {"name1":"Peter","name2":"Jimmy"}
ages = {"age1":28,"age2":25}

# 合并
people = names|ages
people

{‘name1’: ‘Peter’, ‘name2’: ‘Jimmy’, ‘age1’: 28, ‘age2’: 25}

另一种合并的方法:使用update函数,实现原地修改

names.update(ages)  # names直接被修改

names

{‘name1’: ‘Peter’, ‘name2’: ‘Jimmy’, ‘age1’: 28, ‘age2’: 25}

Python装饰器:真高级

修改函数或类的行为

def my_decorator(func):  # 传入被装饰的函数
    def wrapper():  # 装饰器内部的函数
        print("Something is happening before the function is called.")  
        func()  # 执行被装饰的函数
        print("Something is happening after the function is called.")
    return wrapper  # 返回函数本身

@my_decorator
def say_hello():  # 被装饰的函数
    print("Hello!")  # 函数体

say_hello()
Something is happening before the function is called.
Hello!
Something is happening after the function is called.

相关推荐

  1. 8Python代码优雅

    2024-06-08 01:36:01       8 阅读
  2. php开发优雅-ThinkPHP篇

    2024-06-08 01:36:01       15 阅读
  3. 探索ttkbootstrap:Python GUI开发简洁高效

    2024-06-08 01:36:01       24 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-08 01:36:01       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-08 01:36:01       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-08 01:36:01       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-08 01:36:01       18 阅读

热门阅读

  1. 采购管理软件怎么选才不踩坑?收下这14 步清单

    2024-06-08 01:36:01       8 阅读
  2. 【C++】list模拟实现

    2024-06-08 01:36:01       6 阅读
  3. 瀚高数据库相关设置

    2024-06-08 01:36:01       8 阅读
  4. go 源码学习1:scanner学习

    2024-06-08 01:36:01       7 阅读
  5. Python怎么翻转:深度探索与技巧剖析

    2024-06-08 01:36:01       11 阅读
  6. 聚类层次【python,机器学习,算法】

    2024-06-08 01:36:01       10 阅读