Python编程技巧:几个实用的小窍门
发表时间: 2020-02-19 14:36
今天,我们一起回顾下Python Cookbook,全书是以问答对的形式展开,这是我很久之前看的笔记。Cookbook不算是入门书,更像是一本工具书,既然有基础了那就没必要一个个点去看,建议是需要用到那部分就把那块的知识点技巧翻一遍。下面大噶自己查漏补缺吧!
*表达式可以用来将一个含有N个元素的数据结构类型分解成所需的几部分。
1first, *middle, last = grades
例如grades保存了100个成绩数据而我们只关心首末两个成绩,就可以把中间的所有成绩保存到一个列表里面,如下:
保存最后N个元素
1from collection import deque2q = deque()3q.append(1)4q.append(2)5q.append(3)6q.appendleft(4)7q.pop()8q.popleft()
1import heapq23nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]4print(heapq.nlargest(3, nums))5out: [42, 37, 23]6print(heapq.nsmallest(3,nums))7out: [-4, 1, 2]
1In [1]: portfolio = [ 2 ...: {'name': 'IBM', 'shares': 100, 'price': 91.1}, 3 ...: {'name': 'AAPL', 'shares': 50, 'price': 543.22}, 4 ...: {'name': 'FB', 'shares': 200, 'price': 21.09}, 5 ...: {'name': 'HPQ', 'shares': 35, 'price': 31.75}, 6 ...: {'name': 'YHOO', 'shares': 45, 'price': 16.35}, 7 ...: {'name': 'ACME', 'shares': 75, 'price': 115.65} 8 ...: ] 910cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])11cheap12out:13[{'name': 'YHOO', 'price': 16.35, 'shares': 45},14 {'name': 'FB', 'price': 21.09, 'shares': 200},15 {'name': 'HPQ', 'price': 31.75, 'shares': 35}]
1from collections import Counter2words = [一系列单词组成的列表]3word_counts = Counter(words)4top_3 = word_counts.most_common(3)
1from operator import itemgetter 2 3In [26]: rows = [ 4 ...: {'fname': 'Brian', 'lname': 'Jones', 'uid':1003}, 5 ...: {'fname': 'David', 'lname': 'Beazley', 'uid':1002}, 6 ...: {'fname': 'John', 'lname': 'Cleese', 'uid':1001}, 7 ...: {'fname': 'Big', 'lname': 'Jones', 'uid':1004} 8 ...: ] 910itemgetter('fname')11Out[31]: <operator.itemgetter at 0x7f01606657d0>1213rows_by_frame = sorted(rows, key=itemgetter('fname'))14Out[30]:15[{'fname': 'Big', 'lname': 'Jones', 'uid': 1004},16 {'fname': 'Brian', 'lname': 'Jones', 'uid': 1003},17 {'fname': 'David', 'lname': 'Beazley', 'uid': 1002},18 {'fname': 'John', 'lname': 'Cleese', 'uid': 1001}]
1rows_by_frame = sorted(rows, key=itemgetter('fname','lname'))
1>>> round(1.23, 1)21.23>>> round(1.27, 1)41.35>>> round(162773, -1)6162770
1>>>x = 123.4562>>>format(x, '0.2f')3123.46
1>>>import random2>>>values = [1,2,3,4,5,6]3>>>random.choice(values)445>>>random.choice(values)62
1>>>random.shuffle(values)2>>>values3[2,4,3,1,6,5]random.sample()可以取样出N个元素
random.sample()可以取样出N个元素1>>>random.sample(values, 2)2[6, 2]
1from datetime import timedelta 2 3In [33]: a = timedelta(days=2, hours=6) 4In [34]: b = timedelta(hours=4.5) 5In [35]: c = a + b 6In [36]: c.days 7Out[36]: 2 8In [37]: c.seconds 9Out[37]: 3780010In [38]: c.seconds/360011Out[38]: 10.512In [39]: c.total_seconds() / 360013Out[39]: 58.5
1with open('/etc/passwd') as f:2 try:3 while True:4 line = next(f)5 print(line, end='')6 except StopIteration:7 pass
1class Node:2 def __init__(self, value):3 Self._value = vaule4 self._children = []5 def __repr__(self):6 return 'Node({!r})'.format(self._value)7 def __iter__(self):8 return iter(self._children)
在这个例子中,iter()方法将迭代请求转发给对象内部持有的_children属性上。
1def frange(start, stop, increment):2 x = start3 while x < stop:4 yield x5 x += increment
1In [3]: def count(n): 2 ...: while True: 3 ...: yield n 4 ...: n += 1 5 ...: 6In [5]: c = count(0) 7In [6]: c 8Out[6]: <generator object count at 0x7f92899b3c80> 9----> 1 c[0]10TypeError: 'generator' object has no attribute '__getitem__'1112import itertools13In [10]: for x in itertools.islice(c, 10, 20):14 ...: print(x)1510161117121813191420152116221723182419
1from itertools import dropwhile2with open('/etc/passwd') as f:3 for line in dropwhile(lambda line: line,startwith('#'), f):4 print(line, end='')
1In [11]: from itertools import permutations 2In [12]: items = ['a', 'b', 'c'] 3In [13]: for p in permutations(items): 4 ...: print(p) 5 ...: 6('a', 'b', 'c') 7('a', 'c', 'b') 8('b', 'a', 'c') 9('b', 'c', 'a')10('c', 'a', 'b')11('c', 'b', 'a')#如果想得到较短的所有全排列,可以指定长度In [14]: for p in permutations(items, 2): ...: print(p)('a', 'b')('a', 'c')('b', 'a')('b', 'c')('c', 'a')('c', 'b')
1>>>xvalues = [1,5,4,2,10,7] 2>>> yvalues = [101,78,37,15,62,99] 3>>> for x, y in zip(xvalues, yvalues): 4... print(x, y) 5... 61 101 75 78 84 37 92 151010 62117 99
1from itertools import chain 2 3In [18]: a = [1, 2, 3, 4] 4In [19]: b = ['x', 'y', 'z'] 5In [20]: for x in chain(a, b): 6 ...: print (x) 7 ...: 81 9210311412x13y14z
1>>>import heapq 2>>>a = [1,4,7,10] 3>>>b = [2,5,6,11] 4>>>for c in heapq.merge(a,b): 5... print(c) 6... 71 82 9410511612713101411
1with open('somefile.txt', 'rt') as f:2 print('Hello World!', file=f)
1>>>print('GKY',1995,5,18, sep='-',end='!!\n')GKY-1995-5-18!!
1import gzip 2with open('somefile.gz', 'rt') as f: 3 text = f.read() 4 5import bz2 6with open('somefile.bz2', 'rt') as f: 7 text = f.read() 8 9import gzip10with open('somefile.gz', 'wt') as f:11 f.write(text)1213import bz214with open('somefile.bz', 'wt') as f:15 f.write(text)
1import os.path 2def read_into_buffer(filename): 3 buf = bytearray(os.path.getsize(filename)) 4 with open(filename, 'rb') as f: 5 f.readinto(buf) 6 return buf 7 8with open('sample.bin', 'wb') as f: 9 f.write(b'hello world')1011buf = read_into_buffer('sample.bin')12In [16]: buf13Out[16]: bytearray(b'hello world')
1import pickle2data = ... #some python object3f = open('somefile', 'wb')4pickle.dump(data,f)
1import pickle2data = ... #some python object3f = open('somefile', 'wb')4pickle.dumps(data,f)
1from urllib.request import urlopen 2from xml.etree.ElementTree import parse 3 4u = urlopen('http://planet.python.org/rss20.xml') 5doc = parse(u) 6In [24]: for item in doc.iterfind('channel/item'): 7 ....: title = item.findtext('title') 8 ....: date = item.findtext('pubDate') 9 ....: link = item.findtext('link')10 ....: print (title)11 ....: print(date)12 ....: print(link)13 ....: print()14 ....: