1:如何让字典保持有序
from collections import OrderedDict
d=OrderedDict()
2:用户历视记录功能
from collections import deque
q=deque([],5)
pickle.dump(1,open('history','w'))
q2=pickle.load(open('history'))
3:实现可迭代对象和迭代器对象
__iter__实现了此方法可迭代 或者 __getitem__
t=iter(l)
t.next()
实现迭代
from collections import Iterable,Iterator
#气温的迭代器
class WeatherIterator(Iterator):
def __init__(self,cities):
self.cities=cities
self.index=0
def getWeather(self,city)"
....
def next(self):
if self.index==len(self.cities):
raise StopIteration
city=self.cities[self.index]
self.index+=1
return self.getWeather(city)
#可迭代对象
class WeatherIterable(Iterable):
def __init__(self,cities):
self.cities=cities
def __iter__(self):
return WeatherIterator(self.cities)
for x in WeatherIterable([u'北京',u'上海',u'广州'])
print(x)
这一块可以参看:(67条消息) 理解python中的迭代器对象、可迭代对象、生成器对象_helloworld987456的博客-CSDN博客https://blog.csdn.net/helloworld987456/article/details/117407478
4:使用生成器函数实现可迭代对象
生成器:yield
calss P:
def __init__(self,start,end)
self.start=start
self.end=end
def isP(self,k)
if k<2:
return False
for i in xrange(2,k):
if k%i==0:
return False
rerturn True
def __iter__(self):
for k in xrange(self.start,self.end+1)
if self.isP(k):
yield k
for x in P(1,100):
print(x)
5:进行反向迭代以及如何实现反向迭代
l=[1,2,3,4,5]
l.reverse()
l[::-1]
上面两种消耗资源。
iter(l) 得到正向迭代器
reversed(l) 得到反向迭代器
for x in reversed(l):
print(x)
iter需要__iter__
reversed需要__reversed__方法
def __reversed__(self):
t=self.end
while t>=self.start
yield t
t-=self.step
6: 对迭代器做切片操作
from itertools improt islice
islice(f,100,300)
for line islice(f,100,300)
islice(f,500)
islice(f,None)
|