所有可迭代对象可直接解压赋值给多个变量
代码示例
grade = [100,20,30,40,33,55]
first,*middle,last = grade //*middle = [20,30,40,33]
print(avg(middle))
deque可以快速实现队列效果
代码示例
from collections import deque
def dequeTest():
testList = deque(maxlen=3)
testList.append(1)
testList.append(2)
testList.append(3)
print(testList)//deque([1, 2, 3], maxlen=3)
testList.append(4)
print(testList) //deque([2, 3, 4], maxlen=3)
print(list(testList)) //[2,3,4]
heapq可以实现制定数量的最大值或者最小值
代码示例
if __name__ == '__main__':
print("this's main function!")
objectList = [3,5,6,784,23,243,3,2543,3]
getAppointLagerestOrSmallest(3,objectList)
def getAppointLagerestOrSmallest(appointNum,objectList):
resultList = heapq.nlargest(appointNum,objectList)
print(resultList)
resultList = heapq.nsmallest(appointNum,objectList)
print(resultList)
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}
]
expensive = heapq.nlargest(1,portfolio,key=lambda s:s['price']) # 按price字段进行排序,返回结果为单条元素
print("价格最贵为:",expensive) # [{'name': 'AAPL', 'shares': 50, 'price': 543.22}]
objectList = [3,5,6,784,23,243,3,2543,3]
it = heapq.heapify(objectList)
print ('最小值为:',heapq.heappop(objectList)) # 弹出最小的值
print ('最小值为:',heapq.heappop(objectList)) # 弹出最小的值
print ('最小值为:',heapq.heappop(objectList)) # 弹出最小的值
print ('最小值为:',heapq.heappop(objectList)) # 弹出最小的值
OrderedDict可以实现有序字典
代码片段
from collections import OrderedDict
d = OrderedDict()
d['foo'] = 1
d['bar'] = 2
d['spam'] = 3
d['grok'] = 4
for key in d:
print(key,d[key])
# "foo 1", "bar 2","spam 3","grok 4"
OrderedDict可以让字典保持添加进来的顺序,但是同时对空间的消耗是普通链表的量两倍,因为他需要维护链表的顺序
zip()函数
该函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存
代码片段
def zipTest():
testDict = {
"Benz":100,
"BMW":90,
"AUDI":98,
"AUDO":99
}
print(min(testDict)) #AUDI
print(min(zip(testDict.values(),testDict.keys()))) # (90, 'BMW')
字典比较方法
代码示例
def dictCompared():
a = {
'x':1,
'y':2,
'z':3
}
b = {
'w':10,
'x':11,
'y':2
}
print("相同的key:",a.keys()&b.keys())
print('a中特有的key:',a.keys()-b.keys())
print('键值对均相等的:',a.items()&b.items())