#列表
ldata=range(-2,2) #构造列表
a=filter(lambda x :x >0,ldata) #filter函数
b=[x for x in ldata if x > 0] #列表解析
#字典
from random import randint
ddata={k:randint(-2,2) for k in 'abcd'} #构造字典
c={k:v for k,v in ddata.items() if v > 0} #字典解析
#集合
sdata=set(range(-2,2)) #构造集合
d={x for x in sdata if x>0} #集合解析
#传统方式访问
student=('zhangsan',18,'male')
student[0] #name
student[1] #age
student[2] #sex
#定义数值常量,类似其他语言枚举类型
NAME,AGE,SEX=range(3)
student=('zhangsan',18,'male')
student[NAME] #name
student[AGE] #age
student[SEX] #sex
#使用标准库中collections.namedtuple替代内置tuple
from collections import namedtuple
student=namedtuple('student',['name','age','sex'])
s=student('zhangsan',18,'male') #默认赋值,且s仍然是内置tuple类型
s1=student(name='zhangsan',age=18,sex='male') #关键字赋值
s.name #name
s.age #age
s.sex #sex
from random import randint
from collections import Counter
data=[randint(0,20) for _ in range(30)] #创建随机序列,30个值在0-20的元素
c=Counter(data) #构造Counter对象,得到统计频度字典
c1=c.most_common(3) #获取频度最高的3个元素项
print(c1)
from random import randint
# 利用zip将字典转为元组
d= {x:randint(60,100) for x in 'abcxyz'}
t=zip(d.values(),d.keys())
sorted(t) #优先比较value,value相同则比较key
#利用sorted函数的key参数
sorted(d.items(),key=lambda x :x[1])
from random import randint,sample
from functools import reduce
c1={x:randint(1,3) for x in sample('abcxyz',randint(3,6))}
c2={x:randint(1,3) for x in sample('abcxyz',randint(3,6))}
c3={x:randint(1,3) for x in sample('abcxyz',randint(3,6))}
reduce(lambda a,b:a & b,map(dict.keys,[c1,c2,c3]))
有序字典是指字典键值对按照插入顺序存储。网上查找,据说python3.6以前内置的字典是无序的,3.6开始默认有序字典。为确保有序,还是使用有序字典。
from collections import OrderedDict
d=OrderedDict()
d['a']=1
d['b']=2
d['c']=3
for x in zip(d):
print(x)
from collections import deque
import pickle
q=deque([],5) #创建一个容量为5的队列
for i in range(6):
q.append(i)
print(q)
pickle.dump(q,open('history','wb')) #将队列序列化存储
q2=pickle.load(open('history','rb')) #将队列反序列化加载
print(q2)
from itertools import islice
f=open('a.txt','r')
a=f.readlines()[300,500] #需要一次性读取整个文件,占用内存大
b=islice(f,300,500) #取f的300到500行
# islice(f,300) #取f的前300行
# islice(f,300,None) #取f的300行之后
f.close()
from itertools import chain
x=['a','b','c']
y=['1','2','3','4']
#并行迭代
for a,b in zip(x,y):
print(a,b)
#串行迭代
for a in chain(x,y):
print(a)
a='123;456,xyz|hh python'
b=a.split() #['123;456,xyz|hh', 'python']
import re
c=re.split(r'[;,|\s]+',a) #['123', '456', 'xyz', 'hh', 'python']
import re
a='today is 2018-06-20.'
b=re.sub(r'(\d{4})-(\d{2})-(\d{2})',r'\2/\3/\1',a) #today is 06/20/2018.
c=re.sub(r'(?P\d{4})-(?P\d{2})-(?P\d{2})',r'\g/\g/\g',a) #today is 06/20/2018.
s='abc'
s.ljust(10) #abc
s.ljust(10,'-') #abc-------
s.rjust(10) # abc
s.rjust(10,'=') #=======abc
s.center(10) # abc
s.center(10,'*') #***abc****
format(s,'<10') #abc
'{:-<10}'.format(s) #abc-------
format(s,'>10') # abc
format(s,'^10') # abc