1. Exception

import logging

try:
    do_something()
except ValueError:
    logging.exception()
    # some code to handle your exception gracefully if required

2. 变量命名推荐采用下划线方式

如:

def is_empty(sample_arr):
    pass

大小写方式不太Python.

3. 函数默认参数

def add_fruit(fruit, box=None):
    if box is None:
        box = []
        
    box.append(fruit)
    return box

4. 字符串格式化

# Short, crisp and faster!
# f-strings
print(f"Hello, {name}. You are a {profession}.")

5. main 函数

if __name__ == '__main__':
    print('Hello from script!')

在脚本被作为模块导入时,main不会被执行.

6. 条件语句

return 1 if x < 10 else 2

7. 列表迭代

for fruit in list_of_fruits:
    process_fruit(fruit)

8. 迭代时索引

for index, value in enumerate(collection):
    print(index, value)

9. 使用上下文管理器

#context managers
with open("test.csv", "wb") as f:
    f.write("test data")
    v = d["test"]
#即使出现 exception,仍会执行 f.close()

10. 使用 set 而不是 list

s = set(['s', 'p', 'a', 'm'])
l = ['s', 'p', 'a', 'm']

# ok for small no. of elements
def lookup_list(l):
    return 's' in l # O(n)


# better for large no. of elements
def lookup_set(s):
    return 's' in s # O(1)

Python 的 sets 实现是采用 hash 的方式,其复杂度是 O(1),而 list 的复杂度是 O(n).

11. 避免使用 * 导入模块

# bad practice 
from math import *
x = ceil(x)

# good practice 
from math import ceil   
x = ceil(x)

12. 采用 items() 字典迭代

for key,value in d.items():
    print(f"{key} = {value}")
Last modification:June 29th, 2022 at 04:53 pm