Python programming practices (reprint)

Python Programming Practices

Reproduced in: https://github.com/jackfrued/Python-100-Days/blob/master/Python%E7%BC%96%E7%A8%8B%E6%83%AF%E4%BE%8B.md

"Practice" this term refers to "customary practice, the conventional approach, consistent approach", and the word corresponding to the English word called "idiom". Since Python with many other programming languages ​​in grammar and usage is still a relatively significant difference, therefore, as a Python developer if you can not master these practices, you can not write "Pythonic" code. Below we summarize some of the usual code in Python development.

  1. So that the code can either be imported and can be executed.

    if __name__ == '__main__':
  2. Analyzing logic "true" or "false" in the following manner.

    if x:
    if not x:

    Hao code:

    name = 'jackfrued'
    fruits = ['apple', 'orange', 'grape']
    owners = {'1001': '骆昊', '1002': '王大锤'}
    if name and fruits and owners:
        print('I love fruits!')

    Bad code:

    name = 'jackfrued'
    fruits = ['apple', 'orange', 'grape']
    owners = {'1001': '骆昊', '1002': '王大锤'}
    if name != '' and len(fruits) > 0 and owners != {}:
        print('I love fruits!')
  3. Good use in operator.

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

    Hao code:

    name = 'Hao LUO'
    if 'L' in name:
        print('The name has an L in it.')

    Bad code:

    name = 'Hao LUO'
    if name.find('L') != -1:
        print('This name has an L in it!')
  4. Do not use a temporary variable swap two values.

    a, b = b, a
  5. Construction of the sequence string.

    Hao code:

    chars = ['j', 'a', 'c', 'k', 'f', 'r', 'u', 'e', 'd']
    name = ''.join(chars)
    print(name)  # jackfrued

    Bad code:

    chars = ['j', 'a', 'c', 'k', 'f', 'r', 'u', 'e', 'd']
    name = ''
    for char in chars:
        name += char
    print(name)  # jackfrued
  6. EAFP better than LBYL.

    EAFP - Easier to Ask Forgiveness than Permission.

    LBYL - Look Before You Leap.

    Hao code:

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

    Bad code:

    d = {'x': '5'}
    if 'x' in d and isinstance(d['x'], str) \
         and d['x'].isdigit():
        value = int(d['x'])
        print(value)
    else:
        value = None
  7. Use enumerate iterate.

    Hao code:

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

    Bad code:

    fruits = ['orange', 'grape', 'pitaya', 'blueberry']
    index = 0
    for fruit in fruits:
        print(index, ':', fruit)
        index += 1
  8. Generates a list with the formula.

    Hao code:

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

    Bad code:

    data = [7, 20, 3, 15, 11]
    result = []
    for i in data:
        if i > 10:
            result.append(i * 3)
    print(result)  # [60, 45, 33]
  9. Zip combination with keys and values ​​to create a dictionary.

    Hao code:

    keys = ['1001', '1002', '1003']
    values = ['骆昊', '王大锤', '白元芳']
    d = dict(zip(keys, values))
    print(d)

    Bad code:

    keys = ['1001', '1002', '1003']
    values = ['骆昊', '王大锤', '白元芳']
    d = {}
    for i, key in enumerate(keys):
        d[key] = values[i]
    print(d)

Description : The contents of this article are from the network, interested readers can read the original text .

Guess you like

Origin www.cnblogs.com/lebronqjh/p/12190428.html