可迭代的 Python for 循环如何工作? [英] How does a Python for loop with iterable work?

查看:23
本文介绍了可迭代的 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

Iterator 有 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天全站免登陆