python cookbook(1)(每章代码记录,坚持......)
来源:互联网 发布:js购物车 编辑:程序博客网 时间:2024/04/30 05:10
import collectionsimport heapqfrom _collections import defaultdictfrom collections import OrderedDictimport jsonp = (4,5)x, y = pprint(x, y)data = ['ACME', 50, 91.1, (2012,12,21)]name, shares, price, date = dataprint(name, shares, price, date)#p = (4, 5)#x, y, z = ps = 'Hello'a, b, c, d, e = sprint(a, b, c, d, e)_, shares, price, _ = dataprint(shares, price)print("*************************************************")record = ('Dave', 'dave@example.com', '773-555-1212', '847-555-1212')name, email, *phone_numbers = recordprint(name)print(email)print(phone_numbers)print("*************************************************")name, *phone_numbers, email = recordprint(name)print(phone_numbers)print(email)print("*************************************************")line = 'nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false'uname, *fields, homedir, sh = line.split(':')print(uname)print(fields)print(homedir)print(sh)print("*************************************************")record = ('ACME', 50, 123.45, (12,18,2012))name, *_, (*_, year) = recordprint(name, year)print("*************************************************")q = collections.deque(maxlen=3)q.append(1)q.append(2)q.append(3)print(q)q.append(4)print(q)q = collections.deque()q.append(1)q.append(2)q.append(3)print(q)q.appendleft(4)print(q)print(q.pop())print(q)print(q.popleft())print(q)print("*************************************************")nums = [1,8,2,23,7,-4,18,23,42,37,2]print(heapq.nlargest(3, nums))print(heapq.nsmallest(3, nums))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'])expensive = heapq.nlargest(3, portfolio, key=lambda s : s['price'])print(cheap)print(expensive)print("*************************************************")nums = [1,8,2,23,7,-4,18,23,42,37,2]heap = list(nums)print(heap)heapq.heapify(heap)print(heap)print(heapq.heappop(heap))print(heapq.heappop(heap))print(heapq.heappop(heap))print("*************************************************")class PriorityQueue: def __init__(self): self._queue = [] self._index = 0 def push(self, item, priority): heapq.heappush(self._queue, (-priority, self._index, item)) self._index += 1 def pop(self): return heapq.heappop(self._queue)[-1]class Item: def __init__(self, name): self.name = name def __repr__(self): return 'Item({!r})'.format(self.name)q = PriorityQueue()q.push(Item('foo'), 1)q.push(Item('bar'), 5)q.push(Item('spam'), 4)q.push(Item('grok'), 1)print(q)print(q.pop())print(q.pop())print(q.pop())print(q.pop())print("*************************************************")#a = Item('foo')#b = Item('bar')#print(a < b)a = (1, Item('foo'))b = (5, Item('bar'))print(a < b)c = (1, Item('grok'))#print(a < c)d = { 'a' : [1,2,3], 'b' : [4,5]}e = { 'a' : {1,2,3}, 'b' : {4,5}}d = defaultdict(list)d['a'].append(1)d['a'].append(2)d['b'].append(4)print(d)d = defaultdict(set)d['a'].add(1)d['a'].add(2)d['b'].add(4)print(d)d = {}d.setdefault('a', []).append(1)d.setdefault('a', []).append(2)d.setdefault('b', []).append(3)print(d)print("*************************************************")d = OrderedDict()d['foo'] = 1d['bar'] = 2d['spam'] = 3d['grok'] = 4for key in d: print(key, d[key])print(json.dumps(d))print("*************************************************")prices = { 'ACME':45.23, 'AAPL':612.78, 'IBM':205.55, 'HPQ':37.20, 'FB':10.75}min_price = min(zip(prices.values(), prices.keys()))print(min_price)max_price = max(zip(prices.values(), prices.keys()))print(max_price)prices_sorted = sorted(zip(prices.values(), prices.keys()))print(prices)print(min(prices.values()), max(prices.values()))#print(prices[min(prices, key=lambda k : prices[k])])#print(prices[max(prices, key=lambda k : prices(k))])prices = {'AAA':45.23, 'ZZZ':45.23}print(min(zip(prices.values(), prices.keys())))print(max(zip(prices.values(), prices.keys())))print("*************************************************")a = { 'x':1, 'y':2, 'z':3}b = { 'w':10, 'x':11, 'y':2}print(a.keys() & b.keys())print(a.keys() - b.keys())print(a.items() & b.items())c = {key:a[key] for key in a.keys()}print(c)c = {key:a[key] for key in a.keys() - {'z', 'w'}}print(c)print("*************************************************")'''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]print(list(dedupe(a)))'''def dedupe(items, key=None): seen = set() for item in items: val = item if key is None else key(item) if val not in seen: yield item seen.add(val)a = [{'x':1, 'y':2}, {'x':1, 'y':3}, {'x':1, 'y':2}, {'x':2, 'y':4}]print(list(dedupe(a, key=lambda d : (d['x'], d['y']))))print(list(dedupe(a, key=lambda d : d['x'])))print("*************************************************")items = [0,1,2,3,4,5,6]a = slice(2,4)print(a)print(items[a])a = slice(1,6,2)print(items[a])s = 'HelloWorld'print(a.indices(len(s)))for i in range(*a.indices(len(s))): print(i, s[i])print("*************************************************")words = ['look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes','the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the','eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into','my', 'eyes', "you're", 'under']from collections import Counterword_counts = Counter(words)top_three = word_counts.most_common(4)print(top_three)print(word_counts['not'])print(word_counts['eyes'])print("*************************************************")rows = [ {'fname': 'Brian', 'lname': 'Jones', 'uid': 1003}, {'fname': 'David', 'lname': 'Beazley', 'uid': 1002}, {'fname': 'John', 'lname': 'Cleese', 'uid': 1001}, {'fname': 'Big', 'lname': 'Jones', 'uid': 1004}]from operator import itemgetterrows_by_fname = sorted(rows, key=itemgetter('fname'))rows_by_uid = sorted(rows, key=itemgetter('uid'))print(rows_by_fname)print(rows_by_uid)rows_by_lfname = sorted(rows, key=itemgetter('lname', 'fname'))print(rows_by_lfname)print(min(rows, key=itemgetter('uid')))print(max(rows, key=itemgetter('uid')))print("*************************************************")rows = [ {'address': '5412 N CLARK', 'date': '07/01/2012'}, {'address': '5148 N CLARK', 'date': '07/04/2012'}, {'address': '5800 E 58TH', 'date': '07/02/2012'}, {'address': '2122 N CLARK', 'date': '07/03/2012'}, {'address': '5645 N RAVENSWOOD', 'date': '07/02/2012'}, {'address': '1060 W ADDISON', 'date': '07/02/2012'}, {'address': '4801 N BROADWAY', 'date': '07/01/2012'}, {'address': '1039 W GRANVILLE', 'date': '07/04/2012'},]from itertools import groupbyrows.sort(key=itemgetter('date'))for date, items in groupby(rows, key=itemgetter('date')): print(date) for i in items: print(' ', i)print("*************************************************")mylist = [1,4,-5,10,-7,2,3,-1]print([n for n in mylist if n >0]) values = ['1', '2', '-3', '-', '4', 'N/A', '5']def is_int(val): try: x = int(val) return True except ValueError: return Falseivals = list(filter(is_int, values))print(ivals)import mathprint([math.sqrt(n) for n in mylist if n > 0 ]) clip_neg = [n if n > 0 else 0 for n in mylist]print(clip_neg)clip_pos = [n if n < 0 else 0 for n in mylist]print(clip_pos)print("*************************************************")addresses = [ '5412 N CLARK', '5148 N CLARK', '5800 E 58TH', '2122 N CLARK' '5645 N RAVENSWOOD', '1060 W ADDISON', '4801 N BROADWAY', '1039 W GRANVILLE',]counts = [0,3,10,4,1,7,6,1]from itertools import compressmore5 = [n > 5 for n in counts]print(list(compress(addresses, more5)))print("*************************************************")prices = { 'ACME': 45.23, 'AAPL': 612.78, 'IBM': 205.55, 'HPQ': 37.20, 'FB': 10.75} p1 = {key:value for key, value in prices.items()}tech_names = ['AAPL', 'IBM', 'HPQ', 'MSFT']p2 = {key:value for key, value in prices.items() if key in tech_names}print(p2)p3 = dict((key, value) for key, value in prices.items())tech_names = {'AAPL', 'IBM', 'HPQ', 'MSFT'}print(p3)p4 = { key:prices[key] for key in prices.keys() & tech_names }print(p4)from collections import namedtupleprint("*************************************************")Subscriber = namedtuple('Subscriber', ('addr', 'joined'))sub = Subscriber('jonesy@example.com', '2012-10-19')print(sub)print(sub.addr, sub.joined)addr, joined = sub print(addr, joined)Stock = namedtuple('Stock', ['name', 'shares', 'price'])s = Stock('ACME', shares=100, price=123.45)print(s)#s.shares = 75s = s._replace(shares=75)print(s)Stock = namedtuple('Stock', ['name', 'shares', 'price', 'date', 'time'])stock_prototype = Stock('', 0, 0.0, None, None)def dick_to_stock(s): return stock_prototype._replace(**s)a = {'name':'ACME', 'shares':100, 'price':123.45}print(dick_to_stock(a))print("*************************************************")nums = [1,2,3,4,5]s = sum(x * x for x in nums)print(s)s = ('ACME', 50, 123.45)print(','.join(str(x) for x in s))portfolio = [ {'name':'GOOG', 'shares': 50}, {'name':'YHOO', 'shares': 75}, {'name':'AOL', 'shares': 20}, {'name':'SCOX', 'shares': 65}]min_shares = min(s['shares'] for s in portfolio)print(min_shares)print("*************************************************")a = {'x':1, 'z':3}b = {'y':2, 'z':4}from collections import ChainMapc = ChainMap(a, b)print(c)print(c['x'], c['y'], c['z'])print(c.keys())print(list(c.keys()))print(list(c.values()))merged = dict(b)merged.update(a)print(merged)print(merged['x'])print(merged['y'])print(merged['z'])a['x'] = 13print(merged['x'])merged.update(a)print(merged['x'])merged = ChainMap(a, b)print(merged['x'])a['x'] = 42print(merged['x'])
0 0
- python cookbook(1)(每章代码记录,坚持......)
- python cookbook(1)
- python 随机数(python cookbook)
- python cookbook 学习笔记--1
- Chapter 1 for Python Cookbook
- python cookbook(一) 文本
- R Graph cookbook代码(chapter 1-4)
- python cookbook 读书笔记1(字符串处理1)
- Python Cookbook
- python CookBook
- Python-cookbook
- Linux Shell Scripting Cookbook 学习记录1
- python 探索(四) Python CookBook 系统管理
- python数据类型(python cookbook读书笔记一)
- cookbook(1)
- R Graph Cookbook 代码(chapter5-10)
- python cookbook学习笔记十四:函数(1)
- Python Cookbook(第2版)中文版
- VI
- ios下使用rsa算法与php进行加解密通讯
- CMD命令 个人常用
- 关于SlidingMenu侧边栏中的点击事件无效的问题
- Tomcat内存溢出的三种情况及解决办法分析
- python cookbook(1)(每章代码记录,坚持......)
- Micro Benchmarking With Caliper
- MFC中theApp的用法
- Android不再使用Oracle专属的Java API将仅仅依赖于OpenJDK
- PHP 字符串格式化输出
- 二、八、十六进制之间的转换
- Spring+Hibernate报错:Write operations are not allowed in read-only mode (FlushMode.NEVER/MANUAL)
- ubuntu14.04添加右键终端
- iOS Autolayout -- 模块化、等宽高