Python中一些高效的数据操作
- 列表统计
chars = ["a", "b", "a", "c", "a", "d"]
使用count获取单个字符出现次数
chars.count("a")
使用Counter的most_commom获取 出现次数最多的前几位
from collections import Counter
print(Counter(chars).most_common(2)
- 字典键值的集合操作
字典的keys()支持 并集|
交集 &
差集-
等集合操作
dict_a = {"a": 1, "b": 2, "c": 3 }
dict_b = {"a": 1, "c":2, "d": 4}
dict_a.keys() & dict_b.keys()
当字典的values都是字符串(无嵌套)时,字典的items()也支持集合操作
断言字典a包含字典b
assertFalse(dict_b.items() - dict_b.items())
- 列表嵌套字典操作
fruits = [{"name": "apple", "price": 4},
{"name": "orange", "price": 5}, {"name": "pear", "price":6} ,{"name": "apple", "price": 5}]
排序
sorted(fruits, key=lambda x: x["price"])
可以使用itemgetter代替lambda表达式
from operator import itemgetter
sorted(fruits, itemgetter("price"))
最小
mim(fruits, key=lambda x: x["price"])
最大
max(fruits, key=lambda x: x["price"])
使用堆获取最大/最小的前几个
import heapq
heapq.nlargest(2, fruits, key=lambda x: x["price"])
heapq.nsmallest(2, fruits, key=lambda x: x["price"]
分组groupby
from itertools import groupby
groups = groupby(fruits, key=lambda x:x["name"])
for name, fruits in groups:
print(name, len(list(fruits)))
更多学习资料请加添加作者微信:lockingfree获取