Python CookBook(self report)
Python CookBook
中文版:https://python3-cookbook.readthedocs.io/zh_CN/latest/copyright.html
英文版:https://d.cxcore.net/Python/Python_Cookbook_3rd_Edition.pdf
Data Structures and Algorithms
start expressions
items = [1, 10, 7, 4, 5, 9] def sum(items): ... head, *tail = items ... return head + sum(tail) if tail else head ... >>> head, *tail = items >>> head 1 >>> tail [10, 7, 4, 5, 9] >>> sum(items) 36
Deque
Using deque(maxlen=N) creates a fixed-sized queue. When new items are added and the queue is full, the oldest item is automatically removed.
from collections import deque
>>> q = deque(maxlen=3) >>> q.append(1) >>> q.append(2) >>> q.append(3) >>> q deque([1, 2, 3], maxlen=3) >>> q.append(4) >>> q
deque([1, 2, 3])
>>> q.appendleft(4)
>>> q deque([4, 1, 2, 3])
>>> q.pop() 3
>>> q deque([4, 1, 2])
>>> q.popleft() 4
★ Adding or popping items from either end of a queue has O(1) complexity. This is unlike a list where inserting or removing items from the front of the list is O(N).
Heapq
The heapq module has two functions—nlargest() and nsmallest()—that do exactly what you want. For example: import heapq nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2] print(heapq.nlargest(3, nums)) # Prints [42, 37, 23] print(heapq.nsmallest(3, nums)) # Prints [-4, 1, 2] Both functions also accept a key parameter that allows them to be used with more complicated data structures. For example: portfolio = [ {'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} ] cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price']) expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])
声明:如果涉及侵权请联系本人‘删除’,谢谢~
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)