python技巧(7)
2017-01-30 17:13
302 查看
用时访问:需要的时候提取
1.可迭代对象/迭代器对象
可迭代对象如字符串,列表,字典
有:iter,getitem接口
迭代器对象:通过iter(‘可迭代对象’)得到迭代器对象
如
t=iter(‘abcd’)
t.next()
….
2.天气用时访问
下面实现一个天气的迭代器对象和可迭代对象,可以使用collections下的Iterator和Iterable
1.可迭代对象/迭代器对象
可迭代对象如字符串,列表,字典
有:iter,getitem接口
迭代器对象:通过iter(‘可迭代对象’)得到迭代器对象
如
t=iter(‘abcd’)
t.next()
….
2.天气用时访问
import requests city=u'上海':必须是unicode字符串 def getWeather(city): r=requests.get(u'url'+city) data=r.json()['data']['forecast'][0] return '%s:%s,%s'%(city,data['low'],data['high']) city=u'上海':必须是unicode字符串 print getWeather(u'上海')
下面实现一个天气的迭代器对象和可迭代对象,可以使用collections下的Iterator和Iterable
import requests from collections import Iterator,Iterable 迭代器对象(只有next方法) class WeatherIterator(Iterator): def __init__(self,cities): self.cities=cities self.index=0 def __getWeather__(self,city): r=requests.get(u'url'+city) data=r.json()['data']['forecast'][0] return '%s:%s,%s'%(city,data['low'],data['high']) def next(self) if self.index==len(cities): raise StopIteration city=self.cities[self.index] self.index+=1 return getWeather(city) 可迭代对象 class WeatherIterable(Iterable): def __init__(self,cities): self.cities=cities def __iter__(self): return WeatherIterator(self.cities)
相关文章推荐
- Python天天美味(10) - 除法小技巧
- 懒人的Python技巧#20060706
- Python技巧汇总
- Python编程技巧-使用状态机
- 在讨论群看到的一个python技巧
- zt:Python编程技巧笔记
- python技巧31[对象相等性|dictionary模拟switchcase]
- 手把手教您Python多线程应用技巧
- 懒人的Python技巧#20060708
- Python 文件操作技巧(File operation) 实例代码分析
- Python 学习笔记 - 14.技巧(Tips)
- Python 一些细节技巧汇总
- Python 过滤字符串的技巧,map与itertools.imap
- 懒人的Python技巧#20060708
- 懒人的Python技巧#20060706
- Python 文件操作技巧(File operation) 实例代码分析
- python技巧(3)——下划线,私有变量
- 在讨论群看到的一个python技巧
- Python技巧_处理带参数的超长URL