Python知识分享:常用语法糖,用了都说好

前言

Python 中的语法糖是指一些特殊的语法结构,它们并没有引入新的功能,但能够使代码更加简洁易读。下面是一些常用的 Python 语法糖示例,花一点时间学完,你就能撸一手优雅的代码。

正文

1、下划线分割数字,使用下划线来分隔数字可以使得数字更加清晰易读

a = 1000000000  # 打个10亿要去数几个零,麻烦
b = 10_0000_0000  # 清晰
c = 10_5555_5555
print(a, b, c)  # 1000000000 1000000000 1055555555

2、交换值,使用两个变量来交换值,可以使用位运算符 ^ 来避免创建临时变量

b, c = c, b
print(b, c) 

3、范围比较:在 if 语句中使用范围比较可以直接进行条件判断,而不需要进行拆分

if 10 <= a <= 90:
    pass

4、字符串乘法:使用 * 符号可以将字符串重复指定次数

print('-' * 10)  # ----------

5、数组合并:使用 + 符号可以将两个列表合并成一个新的列表

a = [1, 2, 3]
b = [4, 5]
print(a + b)  # [1, 2, 3, 4, 5]

6、数组切片:使用 [] 符号来访问列表中的元素,可以指定切片范围

a = [1, 2, 3, 4, 5, 6, 7]
print(a[3: -1])  # [4, 5, 6],索引3到索引倒数第一位
print(a[-1])     # 7,直接-1是最后一个元素
print(a[:3])     # [1, 2, 3]取前三个元素
print(a[-3:])    # [5, 6, 7]取后三个元素

7、打包解包:使用 *, 符号来打包和解包多个变量值

# 打包操作
a = (10, 'hello', True)   # 创建一个元组
print(type(a))            # 输出结果为 <class 'tuple'>
 
b = [20, 'world']         # 创建一个列表
c = (*b, a[0], *a[1])     # 使用*进行解包操作
print(c)                  # 输出结果为 (20, 'world', 10, 'h', 'e', 'l', 'l', 'o', True)
 
d = {'x': 30}             # 创建一个字典
f = {**d, **{'y': 40}}    # 使用**进行解包操作
print(f)                  # 输出结果为 {'x': 30, 'y': 40}
 
# 解包操作
g = ('apple', 'banana')   # 创建一个元组
h, i = g                  # 使用逗号分隔符进行解包操作
print(h, i)               # 输出结果为 apple banana
 
j = ['cat', 'dog', 'bird']
k, l, m = j                # 使用索引位置进行解包操作
print(k, l, m)             # 输出结果为 cat dog bird
 
n = {'name': 'John', 'age': 25}
p, q = n.items()          # 使用items()函数进行解包操作
print(p, q)               # 输出结果为 name John age 25

8、with 语句:with 语句可以自动管理资源的打开和关闭,无需手动调用 close() 方法

# 一般操作文件为三步走,打开文件 - 读/写文件 - 关闭文件,考虑仔细还得加异常处理
# with语句能自动关闭文件且自动处理异常
with open('test.txt', 'r') as f:
    data = f.read()

9、with 语句的扩展:自定义上下文管理器

class MyNewClass(object):
    #执行with语句时,先执行 __enter__方法,并将返回值复制给 with 后的变量,比如new_class
    def __enter__(self):
        print("Before exect my_function.")
        return self

    # with语句执行完成后,执行 __exit__ 方法,进行收尾、善后(异常处理)等工作,注意*args接收三个参数(exc_type, exc_val, exc_tb)
    # exc_type :若无异常则为 None; 若有异常则为异常类型。
    # exc_val :若无异常则为 None, 若有异常则为异常信息描述。
    # exc_tb :若无异常则为 None, 若有异常则为异常详细追溯信息(TraceBack)。
    def __exit__(self, *args):
        print("After exect my_function.")

    def my_function(self):
        print("Exect my_function.")

with MyNewClass() as new_class:
    new_class.my_function()

10、with 语句的扩展:偷懒版上下文管理器

from contextlib import contextmanager

@contextmanager
def test_new_contextmanager():
    print("Before exect my_function.")  # yield前内容等同于__enter__
    yield  # 需要执行的方法比如后面的 print("After exect my_function.")
    print("Exect my_function.")  # yield前内容等同于__enter__

with test_new_contextmanager() as new_contextmanager:
    print("After exect my_function.")

# Before exect my_function.
# After exect my_function.
# Exect my_function.

11、列表推导式:快速创建一个新的列表

numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print(squares)   # [1, 4, 9, 16, 25]

12、条件表达式:类似于java的三元表达式

x = 10
even_odd = "even" if x % 2 == 0 else "odd"
print(even_odd) # even

13、解构赋值:一次性给多个变量赋值,无需使用中间变量

x, y = 10, 20
# 多个函数返回值:
def get_name():
	return "John", "Doe"

14、装饰器:类似于java的切面编程

def decorator(func):
	def wrapper():
		print("Before function call")
		func()
		print("After function call")
	return wrapper

@decorator
def hello():
	print("Hello, world!")

hello()
# Before function call
# Hello, world!
# After function call

15、内置的 enumerate() 函数:更加便捷的迭代

# 在迭代列表时同时获取索引和元素值
names = ["Alice", "Bob", "Charlie"]
for index, name in enumerate(names):
	print(index, name)
# 0 Alice
# 1 Bob
# 2 Charlie

16、内置的 zip() 函数:同时迭代多个列表

names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
	print(name, age)

# Alice 25
# Bob 30
# Charlie 35

17、any() 和 all() 函数

# 任何一个为True 即为True
list_1 = [0, 0, 0, 1, 0, 0, 0, 0]
print(any(list_1))
# True
list_2 = [False, False, False]
print(any(list_2))
# False

# 任何一个为False 即为False
list_3 = [1, 1, 1, 1, 0, 1, 1, 1]
print(all(list_3))
# False
list_4 = [True, True, True]
print(any(list_4))
# True

18、| 合并字典:版本3.9+,只针对dict

a={'a':1}
b={'b':2}
c={'c':3}
d=a|b|c

print(d)
# {'a': 1, 'b': 2, 'c': 3}

19、类,函数空实现:除了用pass之外,还可以用...

def my_function():
	...
class Person:
	...

20、lambda表达式

# 按字符长度排序一个list
lam_list = ['Java', 'C++', 'Python', 'Golang', 'PHP']
lam_list.sort(key=lambda x: len(x))
print(lam_list)
# ['C++', 'PHP', 'Java', 'Python', 'Golang']

总结

持续更新

  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值