In [2]:
import heapq
nums = [1,8,23,44,56,12,-2,45,23]
print(heapq.nlargest(3,nums))
print(heapq.nsmallest(3,nums))
In [5]:
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(4,portfolio,key = lambda s : s['price'])
expensive = heapq.nlargest(3,portfolio,key = lambda s:s['price'])
In [7]:
print('The fours of cheapest:%s\nThe threes of expensivest:%s'%(cheap,expensive))
In [8]:
heapq.heapify(nums)
nums
Out[8]:
In [9]:
heapq.heappop(nums) # heap -- 堆
Out[9]:
In [22]:
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
'''
push 按照queue 优先级priority 是以从低到高起 若 -priority is 以从高到低起
'''
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)
In [23]:
q = PriorityQueue()
q.push(Item('foo'),1)
q.push(Item('bar'),5)
q.push(Item('spqm'),4)
q.push(Item('grok'),1)
In [17]:
q
Out[17]:
In [24]:
q.pop() # pop 1
Out[24]:
In [25]:
q.pop() # pop 2
Out[25]:
In [26]:
q.pop() # pop 3
Out[26]:
In [21]:
q.pop() # pop 4
Out[21]:
In [1]:
d = {
'a':[1,2,3],
'b':[4,5]
}
e = {
'a':{1,2,3},
'b':{4,5}
}
In [2]:
from collections import defaultdict
In [3]:
d = defaultdict(list)
d['a'].append(1)
d['a'].append(2)
d['b'].append(3)
d = defaultdict(set)
d['a'].add(1)
d['a'].add(2)
d['b'].add(4)
In [4]:
d
Out[4]:
In [6]:
d = {} # a regular dictionary
d.setdefault('a',[]).append(1)
d.setdefault('a',[]).append(2)
d.setdefault('b',[]).append(4)
# 每次都调用需要创建一个新的初始值的instance(empty list=[])
In [7]:
d
Out[7]:
In [17]:
'''
d = {}
pairs = {'a':[1,2],'b':2,'c':3}
for key, value in pairs:
if key not in d:
d[key] = []
d[key].append(value)
'''
In [ ]:
'''
d = defaultdict(list)
for key, value in pairs:
d[key].append(value)
'''
In [29]:
from collections import OrderedDict
def ordered_dict():
d = OrderedDict()
d['foo'] = 1
d['bar'] = 2
d['spa'] = 3
d['gro'] = 4
# Outputs 'foo 1','bar 2','spa 3','gro 4'
ordered_dict()
for key in d:
print(key,d[key])
In [30]:
import json
json.dumps(d)
Out[30]:
In [6]:
prices = {
'AC':45.34,
'AA':615.2,
'IAM':205.3,
'FB':10.765
}
# 对dict进行计算操作 需要利用zip() 将key and value 反转过来
min_price = min(zip(prices.values(),prices.keys()))
print('min_price is %s , %s' % min_price[:])
max_price = max(zip(prices.values(),prices.keys()))
print('max_price is %s , %s' % max_price[:])
In [7]:
prices_sorted = sorted(zip(prices.values(),prices.keys()))
In [8]:
prices_sorted
Out[8]:
In [9]:
prices_and_names = zip(prices.values(),prices.keys())
print(min(prices_and_names))
print(max(prices_and_names))
In [10]:
min(prices)
max(prices)
# 以上是按照key的 字母进行排序并获得最大 or 最小
Out[10]:
In [13]:
min(prices.values())
max(prices.values())
Out[13]:
In [15]:
print(min(prices,key=lambda k:prices[k]))
# print(max(prices,value=lambda v:prices[v]))
In [16]:
p = {'a':123,'b':123}
print(min(zip(p.values(),p.keys())))
print(max(zip(p.values(),p.keys())))