for循环是如何工作的

for循环是如何工作的

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

问题描述

我习惯了for循环的C ++方式,但Python循环让我感到困惑。

  feed.entry:
print party.location.address.text

这里 party feed.entry 中。它是什么意思,它是如何工作的?

解决方案

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

迭代器已next()方法,返回下一个元素或引发异常,所以python for循环实际上是:
$ b $ pre $ iterator = feed.entry .__ iter__ ()
True:
try:
party = iterator.next()
除了StopIteration:
#在最后一个元素
break之后引发StopIteration异常

#循环码
打印party.location.address.text


I am used to the C++ way of for loops, but the Python loops have left me confused.

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

Here party in feed.entry. What does it signify and how does it actually work?

解决方案

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 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循环是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 03:31