python 3-1 如何实现可迭代对象iterable和迭代器对象iterator,__iter__,__getitem__

本文详细介绍了Python中可迭代对象与迭代器对象的概念及其使用方式,通过具体实例展示了如何利用for循环进行迭代,并解释了iter()函数的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

3-1 如何实现可迭代对象和迭代器对象

先看看如何遍历list的

la = [1,2,3]
for x in la: ==>其实是先取得iterator,然后调用iterator.next()
    print x

如下是for循环的迭代的过程

>>> la = [1,2,3]
>>> iterator1 = iter(la)
>>> iterator1.next()
1
>>> iterator1.next()
2
>>> iterator1.next()
3
>>> iterator1.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> 

iter帮助信息

iterable 可迭代对象 list str 都
iterator 迭代器
list 有一个iter方法
str 有一个getitem方法

可迭代对象 只要有iter 或者 getitem都是可迭代对象
迭代器对象 next()

help(iter)
Help on built-in function iter in module builtin:

iter(…)
iter(collection) -> iterator
iter(callable, sentinel) -> iterator

Get an iterator from an object.  In the first form, the argument must
supply its own iterator, or be a sequence.
In the second form, the callable is called until it returns the sentinel.

(END)
print iter(l) = l__iter__()
print iter(s) = l__getitem__()

dir(iter(l) 迭代器对象
[‘class‘, ‘delattr‘, ‘doc‘, ‘format‘, ‘getattribute‘, ‘hash‘, ‘init‘, ‘iter‘, ‘length_hint‘, ‘new‘, ‘reduce‘, ‘reduce_ex‘, ‘repr‘, ‘setattr‘, ‘sizeof‘, ‘str‘, ‘subclasshook‘, ‘next’]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值