python高级编程技巧1——数据结构

列表、字典、集合 根据条件筛选数据

# _*_ 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}

为元组中的每个元素命名,提高程序可读性

#枚举类型,定义一系列数值常量
NAME,AGE,GANDER,EMAIL=xrange(4)
student=('Hayley','24','female','123@163.com')
print student[NAME]


# 使用标准库collections.namedtuple替代内容tuple
from collections import namedtuple

Student=namedtuple('Student',['name','age','gender','email'])
s=Student('Hayley','24','female','123@163.com')
print s.name
print isinstance(s,tuple)  #True

统计序列中元素出现的频度

  • 列表中数字出现的频率
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)

根据字典中值的大小,对字典的项进行排序

d2={x:randint(60,100) for x in 'zxcasd'}
# 利用zip将字典转化成元组
print sorted(zip(d2.itervalues(),d2.iterkeys()))
#传递sorted函数的key参数
print d2.items()
# [('a', 99), ('c', 90), ('d', 98), ('s', 100), ('x', 80), ('z', 62)]
print sorted(d2.items(),key=lambda x:x[1])
# [('z', 63), ('d', 73), ('s', 78), ('x', 81), ('c', 92), ('a', 99)]

快速找到多个字典中的公共键

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

历史记录功能

from collections import deque
q=deque([],3)   #deque 队列
q.append(1)
q.append(2)
q.append(3)
q.append(4)
print list(q)
import pickle  
#pickle提供了一个简单的持久化功能。可以将对象以文件的形式存放在磁盘上。
pickle.dump(q,open('history','w'))
q2=pickle.load(open('history'))
print q2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值