python --cookbook

1---保存有限的历史记录,算是collections.deque的完美应用

2--最大最小

找出最大和最小---max(),min()

从前n个找出前m个最大/最小---heapq.nlargest()/heapq.nsmallest()

如果m接近n---sorted(items)[m:]

from collections import deque
#类利用heqpq模块实现一个简单的优先级队列
import heapq
class Item(object):
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return 'Item({!r})'.format(self.name)
class PriorityQueue(object):
    def __init__(self):
        self._queue = [] #---priviate
        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]

q = PriorityQueue()
q.push(Item('foo'),1)
q.push(Item('bar'),5)
q.push(Item('spam'),4)
print(q.pop())
print(q.pop())
print(q.pop())
View Code

3--有顺序的字典

from collections import OrderedDict
d = OrderedDict() #-----双向链表,内存是普通字典的二倍
d['foo'] = 1
d['bar'] =2
d['spam'] = 3
for key in d:
    print(key)
View Code

4--字典计算

#与字典有关的计算
prices = {
    'apple': 34,
    'pearl': 12,
    'fb':11
}
new_prices = zip(prices.values(),prices.keys())

print(min(prices))
mi = min(prices, key=lambda k: prices[k])
View Code

5---去除重复并且保持有序

#与字典有关的计算

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':3,'y':4},{'x':1, 'y':2},{'x':2,'y':4}]
x = list(dedupe(a, key=lambda d:(d['x'], d['y'])))
print(x)
View Code

6--对切片命名

items = [1,2,3,4,5,6]
a = slice(2,4)
print(a.indices)
#(2,4,1)---start, stop, step
print(items[a])
items[a] = [10,9]
print(items)

 7-使用groupby进行排序,只能检查连续的项,因此要先排序

from operator import itemgetter
from itertools import groupby
rows = [
    {'address':'china', 'date':2013},
    {'address': 'china', 'date': 2011},
    {'address':'china', 'date':2012},
    {'address':'china', 'date':2013},
    {'address': 'china', 'date': 2011},
]
rows.sort(key=itemgetter('date'))
for date, items in groupby(rows, key=itemgetter('date')):
    print(date)
    for i in items:
        print(i)
View Code

 

posted on 2019-02-22 10:32  海豚竹一  阅读(173)  评论(0编辑  收藏  举报

导航