cookpython-day1
python学习
__基于cookbook对python语法的学习
python语法更加简洁,赋值更加灵活
#解压序列赋值给多个变量
a,b=(1,2)
print(a)
print(b)
#可以为多个元素,当数量必须对应
a,b,c,d=['111',2,3,(1,2,3)]
print(a,b,c,d)
#字符串也可赋值
a,b,c,d,e='hello'
print(a,b,c,d,e)
#数量不一致时,增加无关变量,代替位置
a,_,b,_=['111',2,3,(1,2,3)]
print(a)
print(b)
变量和数列个数不符时,*_的操作
#可以用带星号的变量取部分值
a,*b,c=(1,2,3,4,5,6,7,8)
print(b)
#可以用line.split()辅助分割
line = 'nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false'
uname, *fields, homedir, sh = line.split(':')
print(uname,homedir,sh)
# *_可丢弃某些值
a= ('ACME', 50, 123.45, (12, 18, 2012))
name, *_, (*_, year) = a
print(name,year)
deque队列类的使用
用 from collection import deque 导入队列模块
队列的出列,入列的相关操作
#deque的用法 定长,新元素代替最老的元素
from collections import deque
q = deque(maxlen=3)
q.append(1)
q.append(2)
q.append(3)
print(q)
q.append('a')
print(q)
q.append('1234')
print(q)
#也可以不定长
q = deque()
q.append(1)
q.append(2)
q.append(3)
print(q)
q.appendleft(4)
print(q)
q.pop()
print(q)
q.popleft()
print(q)
heapq模块的使用
堆数据结构的相关操作
# heapq模块的nlargest,nsmallest函数 最大数列,最小数列
import heapq
nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37,2 ]
print(heapq.nlargest(3, nums))
print(heapq.nsmallest(3, nums))
a=list(nums)
heapq.heapify(a) #将a[0]置为最小
print(a[0])
print(heapq.heappop(a)) #取出最小的数,次小的数代替a[0]
print(a,a[0])
#加入key=lambda x:x['i'] 参数处理更加复杂的数据结构
list = [
{'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, list, key=lambda s: s['price'])
expensive = heapq.nlargest(3, list, key=lambda s: s['price'])
print(cheap)
print(expensive)
defaultdict类的使用
用 from collection import defaultdict 导入模块
#字典是一个键对应一个值,如果要对应多个值,可以对应一个队列或者集合
d = {
'a' : [1, 2, 3],
'b' : [4, 5]
}
e = {
'a' : {1, 2, 3},
'b' : {4, 5}
}
#defaultdict模块
from collections import defaultdict
d = defaultdict(list) #对应一个队列
d['a'].append(1)
d['a'].append(2)
d['b'].append(4)
print(d)
d = defaultdict(set) #对应一个数组
d['a'].add(1)
d['a'].add(2)
d['b'].add(4)
print(d)
#初始化字典
a=[(1,'one'),(1,'first'),(2,'two'),(2,'double')]
d = defaultdict(list)
for num, en in a:
d[num].append(en)
print(d)
字典的排序问题-OrderedDict类
用 from collections import OrderedDict 导入
from collections import OrderedDict
#OrderedDict会记录录入时的顺序
d = OrderedDict()
d['foo'] = 1
d['bar'] = 2
d['spam'] = 3
d['grok'] = 4
print(d)
for key in d:
print(key, d[key])
字典的运算
最小值,最大值,排序
#股票与价格对应的字典
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
# 用zip函数反转keys和values 只能访问一次
# min,max函数查询
# sorted函数排序 min-max
min_price = min(zip(prices.values(), prices.keys()))#
max_price = max(zip(prices.values(), prices.keys()))
prices_sorted = sorted(zip(prices.values(), prices.keys()))
print(min_price)
print(max_price)
print(prices_sorted)
#不使用zip函数的话,min,max函数作用于键
print(min(prices))
#如果要作用于值
print(min(prices.values()))
#想同时得到键与值的对应
print(min(zip(prices.values(), prices.keys())))
两个字典的运算
#现有以下两个字典,查找其相同点
a = {
'x' : 1,
'y' : 2,
'z' : 3
}
b = {
'w' : 10,
'x' : 11,
'y' : 2
}
print(a.keys()&b.keys()) #相同的键
print(a.keys() - b.keys()) #-集
print(a.items()&b.items()) #相同的项
#过滤字典
c = {key:a[key] for key in a.keys() - {'x', 'y'}}
print(c)
删除序列的相同元素
#构建集合可以删除列表的重复元素
a=[1, 5, 2, 1, 9, 1, 5, 10]
print(set(a))
#但是这样生成的结果中的元素位置被打乱
#若队列的值均为 hashable(可哈希) 类型
a=[1, 5, 2, 1, 9, 1, 5, 10]
def do(items):
seen = set()
for item in items:
if item not in seen:
yield item #yield类似于return,但是不会结束函数
seen.add(item)
print(list(do(a)))
#若队列的值均为 unhashable(不可哈希) 类型,例如dict字典类型
def dedupe(items, key=None):
seen = set()
for item in items:
val = item if key is None else key(item) #key将序列元素转换成 hashable 类型
if val not in seen:
yield item
seen.add(val)
a = [ {'x':1, 'y':2}, {'x':1, 'y':3}, {'x':1, 'y':2}, {'x':2, 'y':4}]
print(list(dedupe(a, key=lambda d: (d['x'],d['y'])))) #删除x键,y键均相同的
print(list(dedupe(a, key=lambda d: d['x']))) #删除x键相同的