python-6-如何?可迭代對象和迭代器對象?

來源:互聯網
上載者:User

python的可迭代對象:list(列表)是可迭代對象,dict(字典)是可迭代對象,string(字串)也是可迭代對象。l = [1,2,3,4]s = 'abcdef'for x in l:print(x)for x in s:print(x)print(iter(l))print(iter(s))

可以由python的內建函數iter得到一個迭代器對象

數組和字串都可以得到一個迭代器對象。

參數要麼支援迭代器,要麼是一個序列

其實,原因是這些迭代器對象都滿足迭代協議的介面;我們調用iter()方法,實際上是調用了l.iter()的方法


而s.getitem是一個序列介面;

列表迭代完畢拋出異常。
所以,for x in l:print(x)的工作機制先由iter(l)得到一個迭代器,就是不停的調用next(),直到拋出異常。
注意可迭代對象和迭代器對象的區別
下面說說一下問題的解決方案

ImportError: No module named 'requests'

requests下載地址
然後pip install 包名

import requestsdef getWeather(city):    r = requests.get(u'http://wthrcdn.etouch.cn/weather_mini?city=' + city)    data = r.json()['data']['forecast'][0]    return '%s: %s , %s' % (city,data['low'],data['high'])print(getWeather(u'保定'))print(getWeather(u'長春'))

import requestsfrom collections import Iterable,Iterator# 氣溫迭代器class WeatherIterator(Iterator):    # 定義構造器,返回哪些城市的天氣(城市名字字串列表)    def __init__(self,cities):        self.cities = cities        # 記錄迭代位置        self.index = 0    def getWeather(self,city):        r = requests.get(u'http://wthrcdn.etouch.cn/weather_mini?city=' + city)        data = r.json()['data']['forecast'][0]        return '%s: %s , %s' % (city,data['low'],data['high'])    # next調用getWeather方法    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'保定',u'湘潭']):    # x就是getWeather return的結果    print(x)

python3,next變成next

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.