10个让你的 Python 代码更具 pythonic 风格的示例
- #1 变量交换
- #2 函数返回元组(自动打包/解包)
- #3 多重比较
- #4 多重比较
- #5 列表推导式
- #6 将 Python 字典当做缓存
- #7 关键字参数
- #8 读取文件
- #9 适用 HTTP
- #10 装饰器
术语 “Pythonic”, 不仅仅意味着使用一些独特的 Python 语法,更重要的是代码的整洁、适用且极具表现力。
下面我收集了 10 个代码片段,通过示例演示一些 “Pythonic” 风格。
#1 变量交换
// C-like code
int temp = a;
a = b;
b = temp;
# Python code
a, b = b, a
在 Python 中,这实际上是通过元组的自动打包/解包将一个元组 (b, a) 分配给另一个 (a, b)。
#2 函数返回元组(自动打包/解包)
// C-like code
struct UserInfo {
char* name,
int age,
char* email
};
UserInfo* get_user_info(uint64_t id) {
// ...
return userInfo;
}
UserInfo* userInfo = get_user_info(id);
// using userInfo->name, userInfo->age, userInfo->email
# Python code
def get_user_info(id):
# ...
return name, age, email
name, age, email = get_user_info(id)
# using name, age, email
#3 多重比较
// C-like code
if (0 <= x && x < y && y <= 100) {
// do something
}
# Python code
if 0 <= x < y <= 100:
# do something
#4 多重比较
// C-like code
if (genre_code == CODE_ROCK ||
genre_code == CODE_COUNTRY ||
genre_code == CODE_JAZZ) {
// do something
}
# Python code
if genre in ("rock", "country", "jazz"):
# do something
#5 列表推导式
// C-like code
float* normalized_buf = malloc(sizeof(float) * buf_size);
for (int i = 0; i < buf_size; i++)
{
normalized_buf[i] = (float)(buf[i] / 255);
}
# Python code
def normalize(x):
return (x/255)
normalized_buf = [normalize(x) for x in buf]
#6 将 Python 字典当做缓存
complex_calc_cache = {} # create an empty dictionary
def complex_calc(m, n, t):
if (m, n, t) in complex_calc_cache:
return complex_calc_cache[(m, n, t)]
else:
# get result after time consuming calculation...
complex_calc_cache[(m, n, t)] = result
return result
Python 允许像(m, n, t)
这样的元组作为字典键。
#7 关键字参数
def init_worker(max_size=1000000, cache_size=1000,
timeout=30000, max_retry=10, encoding="utf-8"):
# ...
return worker
worker1 = init_worker(cache_size=2000)
worker2 = init_worker(max_retry=3)
当函数参数比较多,比较长且带有默认值的时候,关键字参数使用起来会更加方便。
#8 读取文件
file_path = os.path.join("proj", "data", "address.txt")
with open(file_path) as file_obj:
for line in file_obj:
# process one line, e.g. words = line.split()
通过使用 **with** open()
, 在程序退出时,上下文管理 将会自动关闭文件。
#9 适用 HTTP
import requests
import pprint # Pretty Printer
response = requests.get("http://some.url/query")
print("Response is:" + response.text)
pprint.pprint(response.json()) # print in better format
#10 装饰器
import time
def my_decorator(func):
def wrap_profiler(*args, **kwargs):
start_time = time.time()
func(*args, **kwargs)
end_time = time.time()
interval = end_time - start_time
print(f"Function {func.__name__} takes {interval} seconds.")
return wrap_profiler
@my_decorator
def my_test_func():
print("Hello world.")
当我们调用 my_test_func()
函数时, 我们将得到如下结果:
Hello world.
Function my_test_func takes 3.695487976074219e-05 seconds.
最后一个示例涵盖了更多的语法概念,包括 (1) 内部函数、(2) 任意参数列表、(3) 内置变量、(4) 作为一等公民的函数以及 (5) @ 语法糖。
你的 Pythonic 技巧是什么?很高兴在评论中看到您的见解!
翻译自:https://kimi-wh-sun.medium.com/how-to-make-your-python-code-pythonic-9ffda6d19c04
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)