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. leetcode:Reverse Bits

    Reverse bits of a given 32 bits unsigned integer. For example, given input 43261596 (represented in ...

  2. Hbase源码分析:Hbase UI中Requests Per Second的具体含义

    Hbase源码分析:Hbase UI中Requests Per Second的具体含义 让运维加监控,被问到Requests Per Second(见下图)的具体含义是什么?我一时竟回答不上来,虽然大 ...

  3. hdu4760Good Firewall

    4760 数组模拟就可以了 读的时候可以整数读入 #include <iostream> #include<cstdio> #include<cstring> #i ...

  4. find-right-interval

    https://leetcode.com/problems/find-right-interval/ Java里面TreeMap或者TreeSet有类似C++的lower_bound或者upper_b ...

  5. Codeforces Round #272 (Div. 2) D. Dreamoon and Sets (思维 数学 规律)

    题目链接 题意: 1-m中,四个数凑成一组,满足任意2个数的gcd=k,求一个最小的m使得凑成n组解.并输出 分析: 直接粘一下两个很有意思的分析.. 分析1: 那我们就弄成每组数字都互质,然后全体乘 ...

  6. 【MySQL】ERROR 1045 (28000): Access denied for user的解决方法

    去官网下载压缩版的MySQL Server,解压配置path环境变量后.然后克隆my-default.ini创建my.ini文件,在文件中[mysqld]下面配置basedir和datadir bas ...

  7. 推荐 10 款最好的 Python IDE

    简述 Python 非常易学,强大的编程语言.Python 包括高效高级的数据结构,提供简单且高效的面向对象编程. Python 的学习过程少不了 IDE 或者代码编辑器,或者集成的开发编辑器(IDE ...

  8. Qt之QHeaderView自定义排序(获取正确的QModelIndex)

    简述 前几节中分享过关于自定义排序的功能,貌似我们之前的内容已经可以很好地解决排序问题了,但是,会由此引发一些很难发现的问题...比如:获取QModelIndex索引错误. 下面,我们先来实现一个整行 ...

  9. Codeforces 500A - New Year Transportation【DFS】

    题意:给出n个数,终点t 从第i点能够跳到i+a[i],问能否到达终点 #include<iostream> #include<cstdio> #include<cstr ...

  10. BZOJ 4597 随机序列

    一定要想到,对于一个空位如果填了+,那么一定有一个表达式这里填-号使得后面的全部抵消掉.这点十分重要. 于是发现这个答案只和前缀积有关,线段树维护即可. #include<iostream> ...