python小笔记(未完待续)

  1. 解压序列(tuple,list, str) 个数要对应
  2. *星号解压,不确定长度
first,*middle,last=grade
*before,current=records

data=[1,2,3,-1]
*x,y=data
>>>x=[1,2,3]
>>>y=-1
  1. 最大,最小的N个元素
    heap堆 queue 队列 heapq
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'
  1. 手动迭代输出
    迭代是python的一个强大功能
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

你可能感兴趣的:(python)