python cookbook(1)(每章代碼記錄,堅持......)

import collections
import heapq
from _collections import defaultdict
from collections import OrderedDict
import json

p = (4,5)
x, y = p
print(x, y)

data = ['ACME', 50, 91.1, (2012,12,21)]
name, shares, price, date = data
print(name, shares, price, date)

#p = (4, 5)
#x, y, z = p

s = 'Hello'
a, b, c, d, e = s
print(a, b, c, d, e)

_, shares, price, _ = data
print(shares, price)

print("*************************************************")
record = ('Dave', '[email protected]', '773-555-1212', '847-555-1212')
name, email, *phone_numbers = record
print(name)
print(email)
print(phone_numbers)

print("*************************************************")
name, *phone_numbers, email = record
print(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) = record
print(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'] = 1
d['bar'] = 2
d['spam'] = 3
d['grok'] = 4
for 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 Counter
word_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 itemgetter
rows_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 groupby

rows.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 False

ivals = list(filter(is_int, values))
print(ivals)

import math
print([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 compress

more5 = [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 namedtuple

print("*************************************************")
Subscriber = namedtuple('Subscriber', ('addr', 'joined'))
sub = Subscriber('[email protected]', '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 = 75
s = 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 ChainMap

c = 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'] = 13
print(merged['x'])
merged.update(a)
print(merged['x'])

merged = ChainMap(a, b)
print(merged['x'])
a['x'] = 42
print(merged['x'])
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章