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的更多相关文章

  1. Python cookbook - 读书笔记

    Before: python built-in function: docs 我只想学function map(), THIS  - 摘: map(foo, seq) is equivalent to ...

  2. 《The Linux Command Line》 读书笔记01 基本命令介绍

    <The Linux Command Line> 读书笔记01 基本命令介绍 1. What is the Shell? The Shell is a program that takes ...

  3. Linux Shell Scripting Cookbook 读书笔记 1

    本系列文章为<Linux Shell Scripting Cookbook>的读书笔记,只记录了我觉得工作中有用,而我还不是很熟练的命令 书是很好的书,有许多命令由于我比较熟悉,可能就没有 ...

  4. YDKJ 读书笔记 01 Function vs. Block Scope

    Introduction 本系列文章为You Don't Know JS的读书笔记. 书籍地址:https://github.com/getify/You-Dont-Know-JS Scope Fro ...

  5. 硬盘和显卡的访问与控制(一)——《x86汇编语言:从实模式到保护模式》读书笔记01

    本文是<x86汇编语言:从实模式到保护模式>(电子工业出版社)的读书实验笔记. 这篇文章我们先不分析代码,而是说一下在Bochs环境下如何看到实验结果. 需要的源码文件 第一个文件是加载程 ...

  6. Android开发艺术探索读书笔记——01 Activity的生命周期

    http://www.cnblogs.com/csonezp/p/5121142.html 新买了一本书,<Android开发艺术探索>.这本书算是一本进阶书籍,适合有一定安卓开发基础,做 ...

  7. ANTLR3完全参考指南读书笔记[01]

    引用 Terence Parr. The Definitive ANTLR Reference, Building Domain Specific Languages(antlr3 version). ...

  8. OpenCV 2 Computer Vision Application Programming Cookbook读书笔记

    ### `highgui`的常用函数: `cv::namedWindow`:一个命名窗口 `cv::imshow`:在指定窗口显示图像 `cv::waitKey`:等待按键 ### 像素级 * 在灰度 ...

  9. python cookbook学习笔记 第一章 文本(1)

    1.1每次处理一个字符(即每次处理一个字符的方式处理字符串) print list('theString') #方法一,转列表 结果:['t', 'h', 'e', 'S', 't', 'r', 'i ...

随机推荐

  1. xpath选择器使用

    简单说,xpath就是选择XML文件中节点的方法. 所谓节点(node),就是XML文件的最小构成单位,一共分成7种. - element(元素节点)- attribute(属性节点)- text ( ...

  2. SQL高性能查询优化语句

    1.应尽量避免在 where 子句中对字段进行 null 值判断,否则将导致引擎放弃使用索引而进行全表扫描,如: select id from t where num is null可以在num上设置 ...

  3. IntelliJ IDEA12.1.1 使用 相关记录

    最近在切换ide 从eclipse平台上转移到   IDEA 其它的都比较容易,让我烦恼的是使用idea 发布工程,使用tomcat 调试 热部署.期间碰到各种问题,纠结好久了:终于成功完成了,特意记 ...

  4. poj-1469-COURSES-二分图匹配-匈牙利算法(模板)

    题意:N个学生,P个课程,问能不能找到课程的P个匹配. 思路:[早上睡醒了再写] 代码: #include <iostream> #include <cstdio> #incl ...

  5. leetcode:Rotate List

    Given a list, rotate the list to the right by k places, where k is non-negative. For example:Given 1 ...

  6. R语言处理大规模数据集的编程要点

    1.提高程序效率,保证执行速度 (1)尽量使用向量化运算 (2)尽量使用矩阵,必要时才使用数据框 (3)使用read.table时,尽量显式设定colClasses和nrows,设定comment.c ...

  7. R语言中strptime返回值永远为NA的问题

    调用前加上以下代码,即可解决 Sys.setlocale("LC_TIME", "C");

  8. 盒模型padding和margin对滚动条位置的影响

    前置条件:盒模型样式overflow-y:scroll; ①padding-right:15px的效果: padding对于滚动条的位置显然是没有影响的,这也不是我们要的结果(这样很难看!) ②mar ...

  9. VS2015新功能

    今天有幸参加了微软的 Visual Studio Dev Day,趁还没有忘记今天的学习内容. 先把这些内容记录下来,如果有其他人也参加此次交流活动,请补充完善. VS2015新功能 1,Roslyn ...

  10. hdu4604 deque

    题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=4604 思路:就是模拟一下,求每一个开始的非上升和非下降序列.然后求重复的数,由于求出来可能不会是我们想 ...