前言
本文带你学习python的高阶模块。以下内容将帮助加深python的理解
干货
1. 生成式、推导式的用法
Comprehensions,能用一行代码解决的绝不用第二行
gen_list = ['tencent', 'ali', 'baidu', 'huawei', 'bytes', 'meituan', 'didi']
print(list(range(11)))
# if...else 推导式,
print([a for a in gen_list if len(a) > 4])
gen_dict = {
"tencent": 100,
"alibaba": 100,
"baidu": 80,
"huawei": 100,
"bytes": 80,
"meituan": 80,
"didi": 80
}
price2 = {key: value for key, value in gen_dict.items() if value > 90}
print(price2)
names = ['关羽', '张飞', '赵云', '马超', '黄忠']
courses = ['语文', '数学', '英语']
scores = [[None] * len(courses)] * len(names)
print(scores)
print([[None] * len(courses) for _ in range(len(names))])
scores = [[None] * len(courses) for _ in range(len(names))]
for row, name in enumerate(names):
for col, course in enumerate(courses):
scores[row][col] = float(input(f'请输入{name}的{course}成绩: '))
print(scores)
2. heapq模块(堆排序)
数据结构堆(heap)是一种优先队列。使用优先队列能够以任意顺序增加对象,并且能在任意的时间(可能在增加对象的同时)找到(也可能移除)最小的元素
"""
从列表中找出最大的或最小的元素
堆结构(大根堆/小根堆)
"""
import heapq
list1 = [34, 25, 12, 99, 87, 63, 58, 78, 88, 92]
list2 = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'FB', 'shares': 200, 'price': 21.09},
{'name': 'HPQ', 'shares': 35, 'price': 31.75},
{'name': 'YHOO', 'shares': 45, 'price': 16.35},
{'name': 'ACME', 'shares': 75, 'price': 115.65}
]
# 找出列表中最大和最小的n个元素
print(heapq.nlargest(3, list1))
print(heapq.nsmallest(3, list1))
print(heapq.nlargest(2, list2, key=lambda x: x['price']))
print(heapq.nlargest(2, list2, key=lambda x: x['shares']))
3. itertools模块
适用于对列表中排列组合的情况下
"""
迭代工具模块
"""
import itertools
# 产生ABCD的全排列
print([i for i in itertools.permutations('ABCD')])
# [('A', 'B', 'C', 'D'), ('A', 'B', 'D', 'C'), ('A', 'C', 'B', 'D'), ('A', 'C', 'D', 'B'), ('A', 'D', 'B', 'C'), ('A', 'D', 'C', 'B'), ('B', 'A', 'C', 'D'), ('B', 'A', 'D', 'C'), ('B', 'C', 'A', 'D'), ('B', 'C', 'D', 'A'), ('B', 'D', 'A', 'C'), ('B', 'D', 'C', 'A'), ('C', 'A', 'B', 'D'), ('C', 'A', 'D', 'B'), ('C', 'B', 'A', 'D'), ('C', 'B', 'D', 'A'), ('C', 'D', 'A', 'B'), ('C', 'D', 'B', 'A'), ('D', 'A', 'B', 'C'), ('D', 'A', 'C', 'B'), ('D', 'B', 'A', 'C'), ('D', 'B', 'C', 'A'), ('D', 'C', 'A', 'B'), ('D', 'C', 'B', 'A')]
# 产生ABCDE的五选三组合
print([i for i in itertools.combinations('ABCDE', 3)])
# [('A', 'B', 'C'), ('A', 'B', 'D'), ('A', 'B', 'E'), ('A', 'C', 'D'), ('A', 'C', 'E'), ('A', 'D', 'E'), ('B', 'C', 'D'), ('B', 'C', 'E'), ('B', 'D', 'E'), ('C', 'D', 'E')]
# 产生ABCD和123字符的笛卡儿积
print([i for i in itertools.product('ABCD', '123')])
# [('A', '1'), ('A', '2'), ('A', '3'), ('B', '1'), ('B', '2'), ('B', '3'), ('C', '1'), ('C', '2'), ('C', '3'), ('D', '1'), ('D', '2'), ('D', '3')]
4. collections模块
- namedtuple
是一个函数,它用来创建一个自定义的tuple对象,并且规定了tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素
from collections import namedtuple
# 1. 定义一个坐标
point = namedtuple('Point', ['x', 'y'])
# p = point(1, 2)
p = point(11, y=22)
print(p[0], p[1])
# _asdict() 方法用于将namedtuple对象转换成字典
# d = p._asdict()
# print(d, d['x'])
# 可接受不定长参数
# print(point(**d))
# _replace 相当于str.replace()方法
p._replace(x=100)
p1 = point(x=100, y=22)
print(p1[0], p1.x, p[0])
- deque
双端队列,是列表的替代实现,python的列表底层是基于数组来实现,而deque低层是双向链表,因此当需要在头部和尾部添加和删除列表元素时。性能更佳
from collections import deque
q = deque([1, 2, 3, 4, 5])
q.append(6)
q.appendleft(9)
q.extendleft([7, 8, 0])
print(q.index(2))
q.reverse()
print(q, type(q))
- defaultdict
使用dict时,当key存在时,就会抛出KeyError.可以设置一个默认的值。
from collections import defaultdict
d_dict = defaultdict(lambda: 'N/A')
d_dict['key1'] = 'key1'
print(d_dict, d_dict['key2'])
- OrderDict
使用OrderDict可以使字典的key保持有序排列
from collections import OrderedDict
kwargs = {
"task_name": "test1",
"src_data_address": "ec1b2b2a21d8424394c8d2244819312a",
"des_data_address": "f570c36e1d5043f597f41ee91cac2ebf",
"daemon_mode": "on",
"daemon_times": 1,
"bandwidth_limit": "08:00 1M off"
}
order_dict = OrderedDict(**kwargs)
print(order_dict)
arg_dict = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
print(arg_dict)
od_dict = OrderedDict()
od_dict['x'] = 1
od_dict['y'] = 1
od_dict['z'] = 1
print(od_dict) # 按照顺序返回
- Counter
dict的子类,键是元素,值是元素的计数
from collections import Counter
words = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around',
'the', 'eyes', "don't", 'look', 'around', 'the', 'eyes',
'look', 'into', 'my', 'eyes', "you're", 'under'
]
counter = Counter(words)
print(counter.most_common(2))
c = Counter('abcdeabcdabcaba')
# 找出元素中出现频率最高的3个元素
c_common = c.most_common(3)
print(c_common)
# 元素的排序
print(sorted(c))
print(''.join(sorted(c.elements())))
print(sum(c.values()))
# 计算出元素a在Counter中出现的次数
print(c['d'])
# 增加元素
c['e'] = 9
# 删除元素
del c['b']
c.clear()
# 更新增加元素
d = Counter('simsalabim') # make another counter
c.update(d)
print(c)
总结
- 生成式、推导式可以简化代码的书写。使python代码更加的pythonic
- Python中的collections模块封装了字符串,列表,元组,字典的方法。在实际的开发过程中使用这些现成的方法可以提高开发效率。