Python cookbook-读书笔记01
1 数据结构和算法
1.1 Unpacking a sequence into separate variable(解包,赋值)
>>> data = [ 'ACME', 50, 91.1, (2012, 12, 21) ]
>>> name, shares, price, (year, mon, day) = data
#可以用下划线来替代缺省值,节省变量名
>>> >>> data = [ 'ACME', 50, 91.1, (2012, 12, 21) ]
>>> _, shares, price, _ = data
1.2 Unpacking elements from iterables of arbitrary length (从任意长度解包)
*middle可以表示中间的所有域,middle是一个list
def drop_first_last(grades):
first, *middle, last = grades
return avg(middle)
>>> record = ('Dave', 'dave@example.com', '773-555-1212', '847-555-1212')
>>> name, email, *phone_numbers = user_record
>>> phone_numbers
['773-555-1212', '847-555-1212']
处理变长的数据结构和类型:
records = [
('foo', 1, 2),
('bar', 'hello'),
('foo', 3, 4),
]
def do_foo(x, y):
print('foo', x, y) def do_bar(s):
print('bar', s) for tag, *args in records:
if tag == 'foo':
do_foo(*args)
elif tag == 'bar':
do_bar(*args)
1.3 Keeping the last N items
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([2, 3, 4], maxlen=3)
#最右边的第1个元素被抛出
只保留文件最后5行记录:
from collections import deque def search(lines, pattern, history=5):
previous_lines = deque(maxlen=history)
for line in lines:
if pattern in line:
yield line, previous_lines #yield返回一个迭代器
previous_lines.append(line)
# Example use on a file
if __name__ == '__main__':
with open('somefile.txt') as f:
for line, prevlines in search(f, 'python', 5): #遍历迭代器
for pline in prevlines:
print(pline, end='')
print(line, end='')
print('-'*20)
1.4 Finding the largest or smallest N itesms (找到最大或最小的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]
这两个函数可以接受参数key,用来指定复杂结构的排序方法
import heapq
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'])
print (cheap)
#return
[{'price': 16.35, 'shares': 45, 'name': 'YHOO'}, {'price': 21.09, 'shares': 200, 'name': 'FB'}, {'price': 31.75, 'shares': 35, 'name': 'HPQ'}]
1.6 defaultdict()
d = defaultdict(list)
for key, value in pairs:
d[key].append(value)
1.7 Keeping dictionaries in order
OrderedDict()
from collections import OrderedDict
d = OrderedDict()
d['foo'] = 1
d['bar'] = 2
d['spam'] = 3
d['grok'] = 4 for key in d:
print(key, d[key])
# Outputs "foo 1", "bar 2", "spam 3", "grok 4"
1.8 Calculating with dictionaries
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
min_price = min(zip(prices.values(), prices.keys()))
# min_price is (10.75, 'FB')
max_price = max(zip(prices.values(), prices.keys()))
# max_price is (612.78, 'AAPL')
#zip()只能生效一次,再次用需要重新构建
1.9 Finding commonalities in two dictionaries (找到两个字典的相同点)
a = {
'x' : 1,
'y' : 2,
'z' : 3
}
b = {
'w' : 10,
'x' : 11,
'y' : 2
}
# Find keys in common,similar as set
a.keys() & b.keys() # { 'x', 'y' }
# Find keys in a that are not in b
a.keys() - b.keys() # { 'z' }
# Find (key,value) pairs in common
a.items() & b.items() # { ('y', 2) }
#Filter or remove some keys
# Make a new dictionary with certain keys removed
c = {key:a[key] for key in a.keys() - {'z', 'w'}}
# c is {'x': 1, 'y': 2}
1.10 Removing duplicates and maintaining order (去重且保持原来的顺序)
#如果值是可以排序的,例如list
def dedupe(items):
seen = set()
for item in items:
if item not in seen:
yield item
seen.add(item)
>>> a = [1, 5, 2, 1, 9, 1, 5, 10]
>>> list(dedupe(a))
[1, 5, 2, 9, 10]
#如果只是为了去重,则可以用set
>>> a
[1, 5, 2, 1, 9, 1, 5, 10]
>>> set(a)
{1, 2, 10, 5, 9}
#一个有用的场景:读文件的时候过滤掉重复的行
with open(somefile,'r') as f:
for line in dedupe(f):
Python cookbook-读书笔记01的更多相关文章
- Python cookbook - 读书笔记
Before: python built-in function: docs 我只想学function map(), THIS - 摘: map(foo, seq) is equivalent to ...
- 《The Linux Command Line》 读书笔记01 基本命令介绍
<The Linux Command Line> 读书笔记01 基本命令介绍 1. What is the Shell? The Shell is a program that takes ...
- Linux Shell Scripting Cookbook 读书笔记 1
本系列文章为<Linux Shell Scripting Cookbook>的读书笔记,只记录了我觉得工作中有用,而我还不是很熟练的命令 书是很好的书,有许多命令由于我比较熟悉,可能就没有 ...
- YDKJ 读书笔记 01 Function vs. Block Scope
Introduction 本系列文章为You Don't Know JS的读书笔记. 书籍地址:https://github.com/getify/You-Dont-Know-JS Scope Fro ...
- 硬盘和显卡的访问与控制(一)——《x86汇编语言:从实模式到保护模式》读书笔记01
本文是<x86汇编语言:从实模式到保护模式>(电子工业出版社)的读书实验笔记. 这篇文章我们先不分析代码,而是说一下在Bochs环境下如何看到实验结果. 需要的源码文件 第一个文件是加载程 ...
- Android开发艺术探索读书笔记——01 Activity的生命周期
http://www.cnblogs.com/csonezp/p/5121142.html 新买了一本书,<Android开发艺术探索>.这本书算是一本进阶书籍,适合有一定安卓开发基础,做 ...
- ANTLR3完全参考指南读书笔记[01]
引用 Terence Parr. The Definitive ANTLR Reference, Building Domain Specific Languages(antlr3 version). ...
- OpenCV 2 Computer Vision Application Programming Cookbook读书笔记
### `highgui`的常用函数: `cv::namedWindow`:一个命名窗口 `cv::imshow`:在指定窗口显示图像 `cv::waitKey`:等待按键 ### 像素级 * 在灰度 ...
- python cookbook学习笔记 第一章 文本(1)
1.1每次处理一个字符(即每次处理一个字符的方式处理字符串) print list('theString') #方法一,转列表 结果:['t', 'h', 'e', 'S', 't', 'r', 'i ...
随机推荐
- c# 文件简繁体转换
C# 文件简繁体转换 简繁体转换: 方案一: 准确性高,耗性能 方案二: 准确性低,效率高 1 using Microsoft.International.Converters.Tradition ...
- ASP.NET26个性能优化方法
1.数据库访问性能优化 (1)数据库的连接和关闭 访问数据库资源需要创建连接.打开连接和关闭连接几个操作.这些过程需要多次与数据库交换信息以通过身份验证,比较耗费服务器资源. ASP.NET中提供了连 ...
- android下使用smack需引入的包
compile 'org.igniterealtime.smack:smack-android:4.2.0-alpha1' compile 'org.igniterealtime.smack:smac ...
- Win7 系统引导盘(C盘)空间越来越小怎么办?
Win7的系统引导盘用着用着会越来越小.怎么办呢?我以前在网上查过资料,说是找个工具加大C盘.我加了,从原来的20G加到现在的35G.用了一段时间后,空间又只剩几百M了.难道又要加?? 后来,在网上找 ...
- YTU 2619: B 友元类-计算两点间距离
2619: B 友元类-计算两点间距离 时间限制: 1 Sec 内存限制: 128 MB 提交: 469 解决: 252 题目描述 类Distance定义为类Point的友元类来实现计算两点之间距 ...
- 纠结和郁闷的存在感-关于DirectX与HLSL的矩阵存储方式---转载好文章
我常常这么大胆的认为,搞科学的人总是喜欢用各种让常人难以理解的复杂方式去处理某些其实可能很简单的事情,这种情况在他自身擅长的.有着诸多对手竞争的领域上极为常见.比如吧,搞DirectX的人用了左手坐标 ...
- An AnnotationConfiguration instance is required to use
An AnnotationConfiguration instance is required to use <mapping class="jebe7282/study/hibern ...
- 线程——QQ邮件发送
一.造一个QQ邮件发送的窗体 二.开始编写关于邮件发送的代码,以及当点发送按钮的时候,给发送按钮单独造了一个新的线程.这样如果发送的附件太多的话,如果不给发送按钮造新的线程,便会卡住,但是如果给发送按 ...
- Machine Learning for hackers读书笔记(六)正则化:文本回归
data<-'F:\\learning\\ML_for_Hackers\\ML_for_Hackers-master\\06-Regularization\\data\\' ranks < ...
- HDU 1074 Doing Homework
第一次做这道题大概是半个月前了吧,状压DP一个很新鲜的名词 当时看题解怎么也看不懂,现在看懂了以后还是很简单的 所谓状态压缩就是用一个整数的二进制来表示一个状态,比如有三个作业 000表示一科作业也没 ...