python Cookbook

import sys
import numpy as np
# 可迭代对象中分解元素 *表达式
grades=[1,2,2,2,2,2,8]
first,*middle,last=grades
avgs= np.mean(middle)
*trailing,current =[10,8,7,1,9,5,10,3]
# print(trailing)
# print(current)
# *用于拆分
lines="http://www.cnblogs.com:2:3:4heyaqiong/var/empty:/user/bin"
uname,*files,homedir,sh=lines.split(":")
print(uname)
print(sh)
#丢弃
record=('ACME',50,123.45,(12,18,2012))
name,*_,(*_,year)=record
#print(year)
#保留最后N个元素deque

#保留最后N个元素deque 列表容器
#collections这个模块实现专门的容器数据类型提供替代Python的通用内置容器中,dictlistset,和tuple
from collections import deque def search(lines,pattern,history=5): previous_lines=deque(maxlen=history) for line in lines: if pattern in line: yield line ,previous_lines previous_lines.append(line) #if __name__=='__mian__': # with open("somefile.txt")as f: # for line,prevlines in search(f,'python',5): # for pline in prevlines: # print(pline,end='') # print(line,end='') # print('-'*20) q=deque(maxlen=3) q.append(1) q.append(2) q.appendleft(3) q.appendleft(5) q.popleft() #print(q)

#1.4找到最大或最小的N个元素heapq模块该模块提供了堆队列算法的实现,也称为优先级队列算法
import heapq
nums=[1,8,6,7,10,5,-1,-5]
# print(heapq.nlargest(3,nums))
# print(heapq.nsmallest(3,nums))
#可以定义key
portfolio=[{'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(2,portfolio,key=lambda s:s['price'])
expensive=heapq.nlargest(2,portfolio,key=lambda s:s['price'])
#print(cheap,expensive)

#数目N很小时,N大时sort排序
nums=[1,8,6,7,10,5,-1,-5]
heap=list(nums)
heapq.heapify(heap)#在线性时间内将列表x转换为堆
print(heap)
#heap[0]是最小值
min1=heapq.heappop(heap)
print(min1)
min2=heapq.heappop(heap)
print(min2)

heapq.heappush(heap, item)将值推入堆中,保持堆不变。

heapq.heappop(heap)弹出并返回堆中的最小项,保持堆不变。

heapq.heapify(x)在线性时间内将列表x转换为堆。

heapq.nlargest(n, iterable[, key])返回由iterable定义的数据集中n个最大元素的列表。

heapq.nsmallest(n, iterable[, key])返回由iterable定义的数据集中n个最小元素的列表

后两个函数对于较小的n值表现最好。对于较大的值,使用该sorted()函数会更有效。另外,何时n==1使用内置函数min()max()函数更有效。

转载于:https://www.cnblogs.com/heyaqiong/p/10868455.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值