您的位置:首页 > 编程语言 > Python开发

Python技巧:List,Tuple,Dict,Set

2018-03-14 22:32 225 查看
Welcome To My Blog

自己最近主要是用Python,还不是很扎实,学习了程序员硕的Python高效编程技巧实战,讲得很好,感觉受益匪浅,故分享一下心得

一.在列表List,字典Dict,集合Set中根据条件筛选数据

使用各自的生成式即可

产生相同的列表,列表表达式速度比过滤函数快!!将近一倍. 这两种方法都远远快于for循环

过滤函数定义: filter(function or None, sequence) -> list, tuple, or string



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

定义类似于其它语言的枚举类型,也就是定义一系列数值常量

NAME = 0
AGE = 1
EMAL = 2


或者

NAME,AGE,EMAIL = range(3)


具体使用

s1 = ('haes',16,'5065@qq.com')
print s1[AGE]


这么使用得提前设计好数据结构

2. 使用collections.namedtuple替代内置tuple

先实例化一个namedtuple对象,这个对象和tuple的地位一样,只不过带名字(名字就是这个对象的各个属性)

from collections import namedtuple
student = namedtuple('s1',['NAME','AGE','EMAIL'])
s = student('haes',16,'5065@qq.com')
print s.NAME
print isinstance(s,tuple) #Ture


三.统计序列sequence中元素的出现次数

使用sorted函数

#比如:按字典的值排序
new_c = sorted(c.items(),key=lambda x :x[1])


使用collections.Counter对象

将序列sequence传入Counter的构造函数,得到Counter对象是元素出现次数的字典

Counter.most_common(n)方法得到出现次数最多的前n个元素的列表

from collections import Counter
new_c = Counter(data)
print new_c[3] #data中索引为2的元素出现的次数
print new_c.most_common(4) #[(10, 4)说明10出现了4次


四.根据字典值的大小,对字典的项排序

使用sorted函数

from random import randint
d = {x:randint(60,100) for x in 'xyzabc' }
#直接排序是对字典的键排序,因为默认是对各项的第一个元素排序,元组也是
print sorted(d )
#<dictionary-keyiterator object at 0x00000000066742C8>
print iter(d)
#可以通过list看看具体的迭代对象是什么
print list(iter(d))

#使用sorted函数的key参数
b = {x:randint(60,100) for x in range(10)}
#根据value排序和对value排序是两个不同的概念!!!!
new_b1 = sorted(b.items(),key=lambda x:x[1])
new_b2 = sorted(b.values())
new_b3 = sorted(b)
print new_b1
print new_b2
print new_b3


使用zip函数将字典数据转化元组

根据value排序和对value排序是两个不同的概念

zip(seq1, seq2, *more_seqs) 返回的是元组

#zip的使用
new_d = zip(d.values(),d.keys())
#使用迭代版本的key和value节约空间!!!!
new_D = zip(d.itervalues(),d.iterkeys())
print new_D
#将value放在第一个位置,这样就可以按照value排序了
print sorted(new_D)


五.查找多个字典的公共键

step1. 使用字典的viewkeys()方法,得到一个字典keys的集合set

step2. 使用map函数,得到所有字典的keys的集合

step3. 使用reduce函数,得到所有字典的集合的交集set

from random import randint,sample
#先随机生成4个字典
#def sample(self, population, k):
#Chooses k unique random elements from a population sequence.
#sample:从population序列里面随机选取k个
print sample('abcdefg',randint(3,6))
s1 = {k:randint(0,5) for k in sample('abcdefg',randint(3,6)) }
s2 = {k:randint(0,5) for k in sample('abcdefg',randint(3,6)) }
s3 = {k:randint(0,5) for k in sample('abcdefg',randint(3,6)) }
s4 = {k:randint(0,5) for k in sample('abcdef',randint(3,6))}

# print s1.viewkeys() & s2.viewkeys() & s3.viewkeys()
#map对每个元素执行相同的操作
s = map(dict.viewkeys,[s1,s2,s3])
#def reduce(function, sequence, initial=None)
print reduce(lambda a,b:a & b,s)

#用lambda也行
# s = map(lambda x : x.viewkeys(),[s1,s2,s3])
# print reduce(lambda a,b:a & b,s)


六.让字典保持有序

使用collections中的有序字典OrderedDict

#实例化一个OrderedDict对象,然后赋值即可
#先插入的值排在前面
from collections import OrderedDict
d = OrderedDict()
d['Bob'] = 1
d['Jim'] = 21
d['Leo'] = -100
for k in d:
print k


#模拟跑步排名,先记录的说明成绩靠前
from time import time
from random import randint
from collections import OrderedDict
players = list('ABCDEFGH')
start = time()
d = OrderedDict()
for i in range(8):
raw_input()
#pop还能这么用
p = players.pop(randint(0,7-i))
end = time()
print i+1,p,end-start
d[p] = (i+1,end-start)
print "------------------------------------------"
for k in d: print k,d[k]


七.实现用户的历史记录功能

使用collections中的deque,它是一个双端循环队列

程序退出前可以使用pickle将队列对象存入文件,再次运行程序时将其导入

from collections import deque
# deque 双端队列
#def __init__(self, iterable=(), maxlen=None)
#最多存5条,超过5条会把最开始的删掉,从而保持deque的容量为5
q = deque([],5)
q.append(1)
q.append(2)
q.append(3)
q.append(4)
q.append(5)
q.append(6)
print q


#模拟猜数
from random import randint
from collections import deque
import pickle

N = randint(0,100)
history = deque([],5)
def guess(k):
if k==N:
print 'right'
return True
if k<N:
print '%s is less than N'%k
return False
else:
print '%s is greater than N'%k
return False

while(True):
line = raw_input('plz input a number: ')
if line.isdigit():
k = int(line)
history.append(k)
if guess(k):
break;
elif line == 'check':
print list(history)

pickle.dump(history,open('test.txt','wb'))
p = pickle.load(open('test.txt','rb'))
print p
print list(p)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: