1.三元条件运算符:用一行编写简单的 If-Else 结构
min = a if a < b else b
2.列表推导式
Genius = ["Jerry", "Jack", "tom", "yang"]
L1 = [name if name.startswith('y') else 'Not Genius' for name in Genius]
print(L1)
3.联合运算符:合并字典的最简单方法(从 Python 3.9支持)
cities_us = {'New York City': 'US', 'Los Angeles': 'US'}
cities_uk = {'London': 'UK', 'Birmingham': 'UK'}
cities = cities_us|cities_uk
print(cities)
# {'New York City': 'US', 'Los Angeles': 'US', 'London': 'UK', 'Birmingham': 'UK'}
4.F-Strings:Pythonic 字符串格式化技术
pi = 3.1415926
print(f'Pi is {pi}')
print(f'Pi is approximately equal to {pi:.2f}')
# Pi is approximately equal to 3.14
5.使用join()拼接字符串列表
mylist = ["Yang", "Zhou", "is", "writing"]
print(" ".join(mylist))
6.按需导入 Python 模块
如果 my_function 在脚本执行期间从未调用过,则 heavy_module 永远不会加载,从而节省资源并减少脚本的启动时间
def my_function():
import heavy_module
7.使用缓存装饰器
@functools.cache 是 Python 3.9 中引入的一个新特性,用作函数装饰器,以便为单参数或多参数的函数提供一个简单的缓存机制。其作用是存储函数的返回值,当函数再次用相同的参数值调用时,直接从缓存中返回结果,而不是重新执行函数体。这可以显著提高程序性能,特别是对于那些计算成本高昂且被频繁调用的函数
import functools
@functools.cache
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(30))
8.使用 .get() 从字典中检索值
检索不存在的键值时ditch []会引发错误,.get()会返回一个值None ,保持你的代码运行
num_to_words = {1: 'one', 2: 'two', 3: 'three'}
print(num_to_words.get(3))
9.遍历一个集合及其下标
colors = ['red', 'green', 'blue', 'yellow']
for i, color in enumerate(colors):
print (i, '--->', color)
10.列表合并
a = [1, 2, 3]
b = [4, 5, 6]
a.extend(b)
11.使用any和all ny和all用于对序列的布尔值进行逻辑测试
any([False, False, True]) # 返回True
all([True, True, False]) # 返回False