Python for循环可迭代的工作方式是什么? [英] How does a Python for loop with iterable work?

查看:87
本文介绍了Python for循环可迭代的工作方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

for party in feed.entry表示什么,并且此for循环实际上如何工作?

What does for party in feed.entry signify and how does this for-loop actually work?

for party in feed.entry:
    print(party.location.address.text)

(我习惯于使用C ++风格的for循环,但是Python循环使我感到困惑.)

(I am used to C++ style for-loops, but the Python loops have left me confused.)

推荐答案

feed.entry是feed的属性,其值是(例如,如果不是,则此代码将失败)实现迭代协议(例如数组)的对象,并且具有 iter 方法,该方法返回迭代器对象

feed.entry is property of feed and it's value is (if it's not, this code will fail) object implementing iteration protocol (array, for example) and has iter method, which returns iterator object

迭代器具有next()方法,返回下一个元素或引发异常,因此python for循环实际上是:

Iterator has next() method, returning next element or raising exception, so python for loop is actually:

iterator = feed.entry.__iter__()
while True:
    try:
        party = iterator.next()
    except StopIteration:
        # StopIteration exception is raised after last element
        break

    # loop code
    print party.location.address.text

这篇关于Python for循环可迭代的工作方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆