写出高效率python的90个方法,附案例(python3经典编程案例)
Posted cui_yonghua
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了写出高效率python的90个方法,附案例(python3经典编程案例)相关的知识,希望对你有一定的参考价值。
Effective Python摘录。
一. 培养Pythonic思维
1. 查询自己使用的python版本
import sys
print(sys.version_info)
print(sys.version)
# 代码自动检查:https://pylint.org/ pip install pylint
2. 遵循PEP8风格指南
官网:https://pep8.org/
中文翻译:https://www.cnblogs.com/bymo/p/9567140.html
3. 了解bytes与str的区别
bytes:bytes的实例包含原始的8个字节
str:str的实例包含Unicode字符bytes
# 接受str或bytes,并总是返回str的方法
def to_str(bytes_or_str):
if isinstance(bytes_or_str,bytes):
value = bytes_or_str.decode('utf-8')
else:
value = bytes_or_str
return value
# 接受str或bytes,并总是返回bytes的方法:
def to_bytes(bytes_or_str):
if isinstance(bytes_or_str,str):
value = bytes_or_str.encode('utf-8')
else:
value = bytes_or_str
return value
4. 用支持插值的f-string取代C风格的格式字符串和str.format方法
pantry = [
('avocados', 1.25),
('bananas', 2.5),
('cherries', 15),
]
for i, (item, count) in enumerate(pantry):
print(f'{i+1}: {item.title():<10s} = {round(count)}')
5. 用辅助函数取代复杂的表达式
from urllib.parse import parse_qs
my_values = parse_qs('red=5&blue=0&green=3', keep_blank_values=True)
print(repr(my_values))
green_str = my_values.get('green', [''])
if green_str[0]:
green = int(green_str[0])
else:
green = 0
print(f'Green: {green!r}')
def get_first_int(values, key, default=0):
found = values.get(key, [''])
if found[0]:
return int(found[0])
return default
green = get_first_int(my_values, 'green')
print(f'Green: {green!r}')
6. 把数据结构直接拆分到多个变量里,不要专门通过下标访问
snacks = [('bacon', 350), ('donut', 240), ('muffin', 190)]
for i in range(len(snacks)):
item = snacks[i]
name = item[0]
calories = item[1]
print(f'#{i + 1}: {name} has {calories} calories')
for rank, (name, calories) in enumerate(snacks, 1):
print(f'#{rank}: {name} has {calories} calories')
7. 尽量用enumerate取代range
flavor_list = ['vanilla', 'chocolate', 'pecan', 'strawberry']
for flavor in flavor_list:
print(f'{flavor} is delicious')
for i in range(len(flavor_list)):
flavor = flavor_list[i]
print(f'{i + 1}: {flavor}')
# Example
it = enumerate(flavor_list)
print(next(it))
print(next(it))
for i, flavor in enumerate(flavor_list):
print(f'{i}: {flavor}')
for i, flavor in enumerate(flavor_list, 2): # 从2开始
print(f'enumerate {i}: {flavor}')
8. 用zip函数同时遍历两个迭代器
# Example 1
names = ['Cecilia', 'Lise', 'Marie']
counts = [len(n) for n in names]
print(counts, len(counts), len(names))
# Example 2
longest_name = 'None11'
max_count = 0
for i in range(len(names)):
count = counts[i]
if count > max_count:
longest_name = names[i]
max_count = count
print(longest_name)
# Example 3
longest_name = None
max_count = 0
for i, name in enumerate(names):
count = counts[i]
if count > max_count:
longest_name = name
max_count = count
print('--', longest_name)
assert longest_name == 'Cecilia'
# Example 4
longest_name = None
max_count = 0
for name, count in zip(names, counts):
if count > max_count:
longest_name = name
max_count = count
assert longest_name == 'Cecilia'
# Example 5
names.append('Rosalind')
# counts.append(8)
print(f'names: {names}, counts: {counts}')
for name, count in zip(names, counts):
print(name, count)
# Example 6
import itertools
for name, count in itertools.zip_longest(names, counts):
print(f'itertools: {name}: {count}')
9. 不要在for与while循环后面写else块
# Example 1
for i in range(3):
print('Loop', i)
else:
print('Else block!')
# Example
a = 4
b = 9
for i in range(2, min(a, b) + 1):
print('Testing', i)
if a % i == 0 and b % i == 0:
print('Not coprime')
break
else:
print('Coprime')
# 下面是应该的写法:方法一,只要发现某个方法成立,就立刻返回
def coprime(a, b):
for i in range(2, min(a, b) + 1):
if a % i == 0 and b % i == 0:
return False
return True
assert coprime(4, 9)
assert not coprime(3, 6)
# 方法二,用变量记录循环过程中与没有碰到成立的情况,返回这个变量的值
def coprime_alternate(a, b):
is_coprime = True
for i in range(2, min(a, b) + 1):
if a % i == 0 and b % i == 0:
is_coprime = False
break
return is_coprime
assert coprime_alternate(4, 9)
assert not coprime_alternate(3, 6)
10. 用赋值表达式减少重复代码
# -*- encoding: utf-8 -*-
"""
赋值表达式通过海象操作符(:=)给变量赋值,并且让这个值成为这个表达式的结构
"""
FRUIT_TO_PICK = [
{'apple': 1, 'banana': 3},
{'lemon': 2, 'lime': 5},
{'orange': 3, 'melon': 2},
]
def pick_fruit():
if FRUIT_TO_PICK:
return FRUIT_TO_PICK.pop(0)
else:
return []
def make_juice(fruit, count):
return [(fruit, count)]
bottles = []
while fresh_fruit := pick_fruit():
for fruit, count in fresh_fruit.items():
batch = make_juice(fruit, count)
bottles.extend(batch)
print(bottles)
二. 列表与字典
11. 学会对序列做切片
a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
print('Middle two: ', a[3:5])
print('--:', a[-3:-1])
assert a[:5] == a[0:5]
assert a[5:] == a[5:len(a)]
print(a[2:-1])
print(a[-3:-1])
12. 不要在切片里同时 起止下标与步进
x = ['red', 'orange', 'yellow', 'green', 'blue', 'purple']
print(f'odds: {x[::2]}') # odds: ['red', 'yellow', 'blue']
print(f'evens: {x[1::2]}') # evens: ['orange', 'green', 'purple']
print(b'mongoose'[::-1]) # b'esoognom'
13. 通过带星号的unpacking操作来捕获多个元素,不要用切片
car_inventory = {
'Downtown': ('Silver Shadow', 'Pinto', 'DMC'),
'Airport': ('Skyline', 'Viper', 'Gremlin', 'Nova'),
}
((loc1, (best1, *rest1)), (loc2, (best2, *rest2))) = car_inventory.items()
print(f'Best at {loc1} is {best1}, {len(rest1)} others') # Best at Downtown is Silver Shadow, 2 others
print(f'Best at {loc2} is {best2}, {len(rest2)} others') # Best at Airport is Skyline, 3 others
short_list = [1, 2]
first, second, *rest = short_list
print(first, second, rest) # 3 1 2 []
def generate_csv():
yield 'Date', 'Make', 'Model', 'Year', 'Price'
for i in range(3):
yield '2019-03-25', 'Honda', 'Fit', '2010', '$3400'
yield '2019-03-26', 'Ford', 'F150', '2008', '$2400'
all_csv_rows = list(generate_csv())
print(all_csv_rows)
print('CSV Header:', all_csv_rows[0]) # CSV Header: ('Date', 'Make', 'Model', 'Year', 'Price')
print('Row count: ', len(all_csv_rows[1:])) # Row count: 6
# Example 12
it = generate_csv()
header, *rows = it
print('CSV Header:', header) # CSV Header: ('Date', 'Make', 'Model', 'Year', 'Price')
print('Row count: ', len(rows)) # Row count: 6
14. 用sort方法的key参数来表示复杂的排序逻辑
numbers = [93, 86, 11, 68, 70]
numbers.sort(reverse=True) # 由大到小排列
print(numbers)
# Example 2
class Tool:
def __init__(self, name, weight):
self.name = name
self.weight = weight
def __repr__(self):
return f'Tool({self.name!r}, {self.weight})'
tools = [
Tool('level', 3.5),
Tool('hammer', 1.25),
Tool('screwdriver', 0.5),
Tool('chisel', 0.25),
]
# Example 4
print('Unsorted:', repr(tools))
tools.sort(key=lambda x: x.name)
print('Sorted: ', tools) # [Tool('chisel', 0.25), Tool('hammer', 1.25), Tool('level', 3.5), Tool('screwdriver', 0.5)]
# Example 5
tools.sort(key=lambda x: x.weight)
print('By weight:', tools) # [Tool('chisel', 0.25), Tool('screwdriver', 0.5), Tool('hammer', 1.25), Tool('level', 3.5)]
# Example 6
places = ['home', 'work', 'New York', 'Paris']
places.sort()
print('Case sensitive: ', places) # ['New York', 'Paris', 'home', 'work']
places.sort(key=lambda x: x.lower())
print('Case insensitive:', places) # ['home', 'New York', 'Paris', 'work']
15. 不要过分依赖给字典添加条目时所用的顺序
baby_names = {
'cat': 'kitten',
'dog': 'puppy',
}
print(baby_names)
print(list(baby_names.keys()))
print(list(baby_names.values()))
print(list(baby_names.items())) # [('cat', 'kitten'), ('dog', 'puppy')]
print(baby_names.popitem()) # Last item inserted : ('dog', 'puppy')
class MyClass:
def __init__(self):
self.alligator = 'hatchling'
self.elephant = 'calf'
a = MyClass()
for key, value in a.__dict__.items():
print(f'{key} = {value}')
# Example 9
votes = {
'otter': 1281,
'polar bear': 587,
'fox': 863,
}
def populate_ranks(votes, ranks):
names = list(votes.keys())以上是关于写出高效率python的90个方法,附案例(python3经典编程案例)的主要内容,如果未能解决你的问题,请参考以下文章