Python惯例

掌握Python惯例(Python Idioms),写出Pythonic的代码。

  1. 让代码既可以被导入又可以被执行。

    1
    if __name__ == '__main__':
  2. 用下面的方式判断逻辑“真”或“假”。

    1
    if x:
    2
    if not x:

    的代码:

    1
    name = 'CoolR'
    2
    fruits = ['apple', 'orange', 'grape']
    3
    owners = {'1001': 'CoolR', '1002': 'Tom'}
    4
    if name and fruits and owners:
    5
        print('I love fruits!')

    不好的代码:

    1
    name = 'CoolR'
    2
    fruits = ['apple', 'orange', 'grape']
    3
    owners = {'1001': 'CoolR', '1002': 'Tom'}
    4
    if name != '' and len(fruits) > 0 and owners != {}:
    5
        print('I love fruits!')
  3. 善于使用in运算符。

    1
    if x in items: # 包含
    2
    for x in items: # 迭代

    的代码:

    1
    name = 'CoolR'
    2
    if 'R' in name:
    3
        print('The name has an R in it.')

    不好的代码:

    1
    name = 'CoolR'
    2
    if name.find('R') != -1:
    3
        print('This name has an R in it!')
  4. 不使用临时变量交换两个值。

    1
    a, b = b, a
  5. 用序列构建字符串。

    的代码:

    1
    chars = ['C', 'o', 'o', 'l', 'R']
    2
    name = ''.join(chars)
    3
    print(name)  # CoolR

    不好的代码:

    1
    chars = ['C', 'o', 'o', 'l', 'R']
    2
    name = ''
    3
    for char in chars:
    4
        name += char
    5
    print(name)  # CoolR
  6. EAFP优于LBYL。

    EAFP - Easier to Ask Forgiveness than Permission.

    LBYL - Look Before You Leap.

    的代码:

    1
    d = {'x': '5'}
    2
    try:
    3
        value = int(d['x'])
    4
        print(value)
    5
    except (KeyError, TypeError, ValueError):
    6
        value = None

    不好的代码:

    1
    d = {'x': '5'}
    2
    if 'x' in d and isinstance(d['x'], str) and d['x'].isdigit():
    3
        value = int(d['x'])
    4
        print(value)
    5
    else:
    6
        value = None
  7. 使用enumerate进行迭代。

    的代码:

    1
    fruits = ['orange', 'grape', 'pitaya', 'blueberry']
    2
    for index, fruit in enumerate(fruits):
    3
    	print(index, ':', fruit)

    不好的代码:

    1
    fruits = ['orange', 'grape', 'pitaya', 'blueberry']
    2
    index = 0
    3
    for fruit in fruits:
    4
        print(index, ':', fruit)
    5
        index += 1
  8. 用生成式生成列表。

    的代码:

    1
    data = [7, 20, 3, 15, 11]
    2
    result = [num * 3 for num in data if num > 10]
    3
    print(result)  # [60, 45, 33]

    不好的代码:

    1
    data = [7, 20, 3, 15, 11]
    2
    result = []
    3
    for i in data:
    4
        if i > 10:
    5
            result.append(i * 3)
    6
    print(result)  # [60, 45, 33]
  9. 用zip组合键和值来创建字典。

    的代码:

    1
    keys = ['1001', '1002', '1003']
    2
    values = ['CoolR', 'Tom', 'Jerry']
    3
    d = dict(zip(keys, values))
    4
    print(d)

    不好的代码:

    1
    keys = ['1001', '1002', '1003']
    2
    values = ['CoolR', 'Tom', 'Jerry']
    3
    d = {}
    4
    for i, key in enumerate(keys):
    5
        d[key] = values[i]
    6
    print(d)

说明:文章内容源于网络,有兴趣的读者可以阅读原文