Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说
python小抄_初学者怎样看懂代码,希望能够帮助你!!!。
今天,我们一起回顾下Python Cookbook,全书是以问答对的形式展开,这是我很久之前看的笔记。Cookbook不算是入门书,更像是一本工具书,既然有基础了那就没必要一个个点去看,建议是需要用到那部分就把那块的知识点技巧翻一遍。下面大噶自己查漏补缺吧!
*表达式可以用来将一个含有N个元素的数据结构类型分解成所需的几部分。
1first, *middle, last = grades
例如grades保存了100个成绩数据而我们只关心首末两个成绩,就可以把中间的所有成绩保存到一个列表里面,如下:
保存最后N个元素
1from collection import deque 2q = deque() 3q.append(1) 4q.append(2) 5q.append(3) 6q.appendleft(4) 7q.pop() 8q.popleft()
1import heapq 2 3nums = [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 ...: ] 9 10cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price']) 11cheap 12out: 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 Counter 2words = [一系列单词组成的列表] 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 ...: ] 9 10itemgetter('fname') 11Out[31]: <operator.itemgetter at 0x7f0d0> 12 13rows_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.2 3>>> round(1.27, 1) 41.3 5>>> round(, -1)
1>>>x = 123.456 2>>>format(x, '0.2f') 3123.46
1>>>import random 2>>>values = [1,2,3,4,5,6] 3>>>random.choice(values) 44 5>>>random.choice(values) 62
1>>>random.shuffle(values) 2>>>values 3[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]: 37800 10In [38]: c.seconds/3600 11Out[38]: 10.5 12In [39]: c.total_seconds() / 3600 13Out[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 = vaule 4 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 = start 3 while x < stop: 4 yield x 5 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__' 11 12import itertools 13In [10]: for x in itertools.islice(c, 10, 20): 14 ...: print(x) 1510 1611 1712 1813 1914 2015 2116 2217 2318 2419
1from itertools import dropwhile 2with 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 15 1010 62 117 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 92 103 114 12x 13y 14z
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 94 105 116 127 1310 1411
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 gzip 10with open('somefile.gz', 'wt') as f: 11 f.write(text) 12 13import bz2 14with 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') 10 11buf = read_into_buffer('sample.bin') 12In [16]: buf 13Out[16]: bytearray(b'hello world')
1import pickle 2data = ... #some python object 3f = open('somefile', 'wb') 4pickle.dump(data,f)
1import pickle 2data = ... #some python object 3f = 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 ....:
今天的分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。