Hand touch hand to teach you how to do the small details big optimized coding in Python

Hand touch hand to teach you how to do the small details big optimized coding in Python

Count in the list

"""
在列表里计数,使用 Python 原生函数计数要快很多,所以尽量使用原生函数来计算。
"""
elements = list(range(1, 1000001))

# 常见写法
num = 0
for n in elements:
    num += 1

# 建议写法
len(elements)

A filter list

"""
过滤一个列表,推导列表的方式最快。
"""
elements = list(range(1, 1000001))

# 第一种,常见写法
l = []
for e in elements:
    if e % 2:
        l.append(e)

# 第二种,常见写法。filter 增加了复杂度,返回一个迭代对象再用 list 转成一个列表,这样会增加开销。
list(filter(lambda e : e % 2, elements))

# 建议写法,推导的方式性能最佳
[e for e in elements if e % 2]

Use exceptions to check property

"""
灵活使用异常检查属性
"""
class User(object):
    name = 'Python'

# 常见写法,通过内置函数 hasattr 检查,查找内部类的属性增加了开销。
user = User()
if hasattr(user, 'name'):
    user.name

# 建议写法,通过异常捕获
start = timeit.default_timer()
try:
    user.name
except AttributeError:
    pass

Check the list of elements

"""
检查列表元素
"""
elements = list(range(1, 1000001))

# 常见写法,使用循环的方式检查
def check_number(n):
    for e in elements:
        if e == n:
            return True
    return False
check_number(10000)

# 建议写法,直接使用 in 检查列表
10000 in elements

List deduplication

"""
列表去重
"""
elements = list(range(1, 10001))

# 常见写法,使用循环的去重列表
u = []
for e in elements:
    if e not in u:
        u.append(e)

# 建议写法,使用 set 对列表去重
set(elements)

List sorted

"""
列表排序
"""
elements = list(range(1, 100001))

# 常见写法,sorted 函数会把原来的列表进行排序后,再返回一个新的列表。
sorted(elements)

# 建议写法,sort 函数直接在原来的列表上排序。
start = timeit.default_timer()
elements.sort()

The iterative loop into the function

"""
将迭代循环放入函数
"""
# 常见写法,循环调用 1000 函数。
def cube(n):
    return n**3
cubes = [cube(e) for e in range(1000)]

# 建议写法,把重复的循环一次性塞入函数。
def compute_cubes():
    return [e**3 for e in range(1000)]
compute_cubes()

Check whether to True

"""
检查是否为 True
"""
var = True
# 第一种,常见写法。== 会调用魔术函数 __eq__ 来比较左右两边的类型。
if var == True:
    pass

# 第二种,常见写法。使用 is 来判断。
if var is True:
    pass

# 建议写法,直接使用这种方式来判断,是否为空、是否为 None、是否为空 list、是否为空 dict 会比较快。
if var:
    pass

Check if the list is empty

"""
检查列表是否为空
"""
l = []
# 第一种,常见写法。
if len(l) == 0:
    pass

# 第二种,常见写法。
if l == []:
    pass

# 建议写法,这种方式最快。
if not l:
    pass

Generating a list or dict

"""
生成一个 list or dict
"""
# 常见写法,使用 list 生成一个对象,会产生开销。
list()

# 建议写法,[] 直接返回一个 list,开销较小。
[]

# 第三种方式,{} 直接返回一个 dict,开销较小。
{}

Compare Chain

# 常见写法
a = 5
if a > 1 and a < 7:
    pass

# 建议写法
if 1 < a < 7:
    pass

Variable exchange

# 常见写法
x = 10
y = 5
tmp = x
x = y
y = tmp

# 建议写法
x = 10
y = 5
x, y = y, x

Ternary operator

# 常见写法
a = 10
b = 5
if a > b:
    c = a
else:
    c = b

# 建议写法
c = a if a > b else b

Mosaic character list

# 常见写法
l = ['a', 'b', 'c', 'd']
str = ''
for e in l:
    str = str + e

# 建议写法
str = ''.join(l)

Formatting characters

# 常见写法
name = "tony"
age = 100
str = "myname : " + name + " my age : " + str(age)
str = "myname : %s my age : %d" % (name, age)

# 建议写法
str = "myname : {} my age {}".format(name, age)

Filter List

# 常见写法
mylist = range(20)
odd_list = []
for e in mylist:
    if e % 2 == 1:
        odd_list.append(e)

# 建议写法
odd_list = [e for e in mylist if e % 2 == 1]

Filter Dictionary

# 常见写法
user_list = [{'name': 'lucy', 'email': '[email protected]'}, {'name': 'lily', 'email': '[email protected]'}]
user_email = {}
for user in user_list:
    if 'email' in user:
        user_email[user['name']] = user['email']

# 建议写法
{user['name']: user['email'] for user in user_list if 'email' in user}

Conditional

# 常见写法
if l = []:
    pass
    
# 建议写法
if l:
    pass
    
# 常见写法
if something == None:
    pass
    
# 建议写法
if something is None:
    pass

emumerate instead of access to the index variables for loop

# 常见写法
my_container = ['lily', 'lucy', 'tom']
index = 0
for element in my_container:
    print('{} {}'.format(index, element))
    index += 1

# 建议写法
for index, element in enumerate(my_container):
    print('{} {}'.format(index, element))

Avoid the use of a variable (the mutable) variable as a function of parameters to their default initialization value

# 常见写法
def function(l = []):
    l.append(1)
    return l

print function()
print function()
print function()

# print
[1]
[1, 1]
[1, 1, 1]

# 建议写法,使用 None 作为可变对象占位符
def function(l=None):
    if l is None:
      l = []
    l.append(1)
    return l

Complete switch case of a dictionary object function

# 常见写法
def apply_operation(left_operand, right_operand, operator):
    if operator == '+':
        return left_operand + right_operand
    elif operator == '-':
        return left_operand - right_operand
    elif operator == '*':
        return left_operand * right_operand
    elif operator == '/':
        return left_operand / right_operand

# 建议写法
def apply_operation(left_operand, right_operand, operator):
    import operator as op
    operator_mapper = {'+': op.add, '-': op.sub, '*': op.mul, '/': op.truediv}
    return operator_mapper[operator](left_operand, right_operand)

Everything Objects

# 常见写法
def get_size(some_object):
    try:
        return len(some_object)
    except TypeError:
        if some_object in (True, False, None):
        return 1
    else:
        return int(some_object)

print(get_size('hello'))
print(get_size([1, 2, 3, 4, 5]))
print(get_size(10.0))

# 建议写法
def get_size(some_object):
    if isinstance(some_object, (list, dict, str, tuple)):
        return len(some_object)
    elif isinstance(some_object, (bool, type(None))):
        return 1
    elif isinstance(some_object, (int, float)):
        return int(some_object)

Guess you like

Origin www.cnblogs.com/yxhblogs/p/11116973.html