1 多多应用列表生成式
替换上面代码:
cube_numbers = [] for n in range(0,10): if n % 2 == 1: cube_numbers.append(n**3)
为列表生成式写法:
cube_numbers = [n**3 for n in range(1,10) if n%2 == 1]
2 内置函数
尽可能多应用上面这些内置函数:
3 尽可能应用生成器
单机解决较大数据量时,生成器往往很有用,因为它是分小片逐次读取,最大水平节俭内存,如下网页爬取时应用 yield
import requests
import re
def get_pages(link):
pages_to_visit = []
pages_to_visit.append(link)
pattern = re.compile('https?')
while pages_to_visit:
current_page = pages_to_visit.pop(0)
page = requests.get(current_page)
for url in re.findall('<a href="([^"]+)">', str(page.content)):
if url[0] == '/':
url = current_page + url[1:]
if pattern.match(url):
pages_to_visit.append(url)
# yield
yield current_page
webpage = get_pages('http://www.example.com')
for result in webpage:
print(result)
4 判断成员所属关系最快的办法应用 in
for name in member_list:
print('{} is a member'.format(name))
5 应用汇合求交加
替换上面代码:
a = [1,2,3,4,5]
b = [2,3,4,5,6]
overlaps = []
for x in a:
for y in b:
if x==y:
overlaps.append(x)
print(overlaps)
批改为 set 和求交加:
a = [1,2,3,4,5]
b = [2,3,4,5,6]
overlaps = set(a) & set(b)
print(overlaps)
6 多重赋值
Python 反对多重赋值的格调,要多多应用
first_name, last_name, city = "Kevin", "Cunningham", "Brighton"
7 尽量少用全局变量
Python 查找最快、效率最高的是局部变量,查找全局变量绝对变慢很多,因而多用局部变量,少用全局变量。
8 高效的 itertools 模块
itertools 模块反对多个迭代器的操作,提供最节俭内存的写法,因而要多多应用,如下求三个元素的全排列:
import itertools
iter = itertools.permutations(["Alice", "Bob", "Carol"])
list(iter)
9 lru_cache 缓存
位于 functools 模块的 lru_cache 装璜器提供了缓存性能,如下联合它和递归求解斐波那契数列第 n:
import functools
@functools.lru_cache(maxsize=128)
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
return fibonacci(n - 1) + fibonacci(n-2)
因而,上面的递归写法十分低效,存在反复求解多个子问题的状况:
def fibonacci(n):
if n == 0: # There is no 0'th number
return 0
elif n == 1: # We define the first number as 1
return 1
return fibonacci(n - 1) + fibonacci(n-2)
10 内置函数、key 和 itemgetter
下面提到尽量多应用内置函数,如下对列表排序应用 key,
import operator
my_list = [("Josh", "Grobin", "Singer"), ("Marco", "Polo", "General"), ("Ada", "Lovelace", "Scientist")]
my_list.sort(key=operator.itemgetter(0))
my_list
最近整顿了几百 G 的 Python 学习材料,蕴含新手入门电子书、教程、源码等等,收费分享给大家!想要的返回“Python 编程学习圈”,发送“J”即可收费取得