cookbok学习心得

编程入门 行业动态 更新时间:2024-10-27 17:11:22

cookbok<a href=https://www.elefans.com/category/jswz/34/1765834.html style=学习心得"/>

cookbok学习心得

cookbok学习心得

第一章

序列赋多个值

>>> p = (4, 5)
>>> x, y = p
>>> data = [ 'ACME', 50, 91.1, (2012, 12, 21) ]
>>> name, shares, price, date = data
>>> data = [ 'ACME', 50, 91.1, (2012, 12, 21) ]
>>> _, shares, price, _ = data

列表元组等均可,但双方元素个数必须匹配,可通过任意变量名去占位。
为解决匹配问题,可使用星号表达式:

>>> first, *middle, last = grades
>>> name, email, *phone_numbers = record
#字符串分割
>>> line = 'nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false'
>>> uname, *fields, homedir, sh = line.split(':')
#列表分割
>>> items = [1, 10, 7, 4, 5, 9]
>>> head, *tail = items
#递归算法
>>> def sum(items):
...     head, *tail = items
...     return head + sum(tail) if tail else head

保留最后 N 个元素

from collections import dequedef search(lines, pattern, history=5):previous_lines = deque(maxlen=history)for line in lines:if pattern in line:yield line, previous_linesprevious_lines.append(line)# Example use on a file
if __name__ == '__main__':with open(r'../../cookbook/somefile.txt') as f:for line, prevlines in search(f, 'python', 5):for pline in prevlines:print(pline, end='')print(line, end='')print('-' * 20)

使用 deque(maxlen=N) 构造函数会新建一个固定大小的队列。当新的元素加入并且这个队列已满的时候, 最老的元素会自动被移除掉。
deque 类可以在队列的两端执行添加和弹出元素的操作。

>>> 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

一个集合中获得最大或者最小的 N 个元素列表

heapq 模块有两个函数:nlargest() 和 nsmallest()

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]portfolio = [{'name': 'IBM', 'shares': 100, 'price': 91.1},{'name': 'AAPL', 'shares': 50, 'price': 543.22},{'name': 'FB', 'shares': 200, 'price': 21.09},
]
cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])
expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])
>>> nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
>>> import heapq
>>> heap = list(nums)
>>> heapq.heapify(heap)
>>> heap
[-4, 2, 1, 23, 7, 2, 18, 23, 42, 37

更多推荐

cookbok学习心得

本文发布于:2024-02-12 01:18:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1684895.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:学习心得   cookbok

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!