# _*_ coding:utf-8 _*_
_author_ = 'hayley'
_date_ = '2018/6/16 21:38'
from random import randint
# 列表
# 生成 10个 -10~10的随机数,过滤出大于0的数
l=[randint(-10,10) for x in xrange(10)]
# filter函数 依次迭代data中的数
print filter(lambda x: x >= 0, l)
#列表解析
print [x for x in l if x>=0]
# timeit命令查看运行时间,列表解析速度是filter速度的一半,都远快于迭代
# 字典
d={x:randint(60,100) for x in xrange(1,20)}
print {k:v for k,v in d.iteritems() if v>90}
#集合
s=set(l)
print {x for x in s if x%3==0}
l2=[randint(0,20) for _ in xrange(30)]
c=dict.fromkeys(l2,0)
for x in l2:
c[x]+=1
print c
from collections import Counter
c=Counter(l2)
print c.most_common(3) #参数为取几个值
段落中单词出现的频率
str='''A man is driving up a steep, narrow mountain road. a woman is driving down the same road.
As they pass each other, the woman leans out of the window and yells "pig!!"
The man immediately leans out of his window and replies, "witch!!"
They each continue on their way, and as the man rounds the next corner, he crashes into a pig in the middle of the road.
if only men would listen.'''
import re
print Counter(re.split('\W+',str)).most_common(3)
from random import sample
print sample('qwertyu',randint(3,6)) #sample取样,取第一个参数中的任意3-6个
t1={x:randint(1,4) for x in sample('qwertyu',randint(3,6))}
t2={x:randint(1,4) for x in sample('qwertyu',randint(3,6))}
t3={x:randint(1,4) for x in sample('qwertyu',randint(3,6))}
# 集合取并集
print t1.viewitems()&t2.viewitems()&t3.viewitems()
# 数据量多的时候
print reduce(lambda a,b:a&b,map(dict.viewkeys,[t1,t2,t3 ]))
让字典保持有序
from collections import OrderedDict
ds=OrderedDict()
ds['A']=(1,22)
ds['B']=(2,12)
ds['C']=(3,36)
for k in ds:print k