first,*middle,last=grade
*before,current=records
data=[1,2,3,-1]
*x,y=data
>>>x=[1,2,3]
>>>y=-1
import heapq
a=[1,8,2,34,7,-4,19,2]
heapq.nlargest(3,a)
>>> [34, 19, 8]
# 排序
heapq.heapify(a)
a
>>>[-4, 2, 1, 8, 7, 2, 19, 34]
更复杂的,加参数
dataset= [
{'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,dataset,key=lambda s: s['price'])
>>>[{'name': 'YHOO', 'price': 16.35, 'shares': 45},
{'name': 'FB', 'price': 21.09, 'shares': 200},
{'name': 'HPQ', 'price': 31.75, 'shares': 35}]
4.数字四舍五入和格式化输出
4.1 浮点数四舍五入
x=123.4567
round(x,2)
>>>123.46
round(x,-1)
>>120.0
round(x,-2)
>>100.0
4.2格式化输出
format(x,'0.2f')
'123.46'
def manual_iter(a):
i=iter(a)
try:
while True:
print("i=",next(i)
except StopIteration:
pass
a=[1,2,3]
manual_iter(a)
>>> i=1
i=2
i=3