4.4 可迭代对象(Iterable)与迭代器(Iterator)

4.4 可迭代对象(Iterable)与迭代器(Iterator)

4.4.1 可迭代(Iterable)对象
如果一个对象实现了__iter__方法,那么这个对象就是可迭代(Iterable)对象
>>> #如何知道一个对象实现了那些方法,请使用help(对象)函数?
>>> help(list)
Help on class list in module builtins:

class list(object)
 |  list(iterable=(), /)
 |
 |  Built-in mutable sequence.
 |
 |  If no argument is given, the constructor creates a new empty list.
 |  The argument must be an iterable if specified.
 |
 |  Methods defined here:
 |
 |  __add__(self, value, /)
 |      Return self+value.
 |
 |  __contains__(self, key, /)
 |      Return key in self.
 |
 |  __delitem__(self, key, /)
 |      Delete self[key].
 |
 |  __eq__(self, value, /)
 |      Return self==value.
 |
 |  __ge__(self, value, /)
 |      Return self>=value.
 |
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |
 |  __gt__(self, value, /)
 |      Return self>value.
 |
 |  __iadd__(self, value, /)
 |      Implement self+=value.
 |
 |  __imul__(self, value, /)
 |      Implement self*=value.
 |
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  __iter__(self, /)
 |      Implement iter(self).
 |
 |  __le__(self, value, /)
 |      Return self<=value.
 |
 |  __len__(self, /)
 |      Return len(self).
 |
 |  __lt__(self, value, /)
-- More  --

我们还可以通过调用Python内置函数isinstance()来判断一个对象是否属于可迭代(Iterable)对象。

在这里插入图片描述

不是可迭代对象:数字

可迭代对象:列表,元组,字典,集合,字符串,range对象

4.4.2 迭代器
实现了__iter__方法和__next__方法,并且可以通过__next__方法不断返回下一个值的对象称为迭代器(Iterator)。迭代器(Iterator)还可以通过内置函数next()访问下一个元素。

通过调用Python内置函数isinstance()来判断一个对象是否属于迭代器(Iterator)

在这里插入图片描述

列表,元组,字典,集合,字符串,range对象,数字,都不属于迭代器。


虽然列表、元组、字符串、字典、集合都是可迭代(Iterable)对象而不是迭代器(Iterator),但可以通过iter()函数获得一个迭代器(Iterator)

>>> from collections.abc import Iterator
>>> list=[1,2,3,4,5]
>>> isinstance(list,Iterator)
False
>>> #使用iter()函数获得一个迭代器
>>> list_iter=iter(list)
>>> isinstance(list_iter,Iterator)
True
>>> #返回下一个值
>>> list_iter.__next__()
1
>>> list_iter.__next__()
2
>>> #使用内置函数next()访问下一个元素
>>> next(list_iter)
3
>>> next(list_iter)
4
>>> next(list_iter)
5
>>> next(list_iter)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> #没有下一个元素,则会触发StopIteration异常
4.4.3 相关内置函数
enumerate()

enumerate(iterable,start=0)

返回一个enumerate对象---下标和值,第一个参数表示可迭代对象,第二个参数表示下标的开始值,默认从0开始。

enumerate对象即是可迭代对象也是可迭代器

list(),tuple(),dict(),set()函数能将可迭代对象转换为列表、元组、字典、集合。

>>> l=['a','b']
>>> e=enumerate(l)
>>> e
<enumerate object at 0x0000022B06394B80>
>>> type(e)
<class 'enumerate'>
>>> from collections.abc import Iterator
>>> isinstance(e,Iterator)
True
>>> #enumerate 对象转为列表list
>>> list(e)
[(0, 'a'), (1, 'b')]
>>> #enumeratr对象转为元组tuple,同时设置输出下标开始值为2
>>> #设置enumerate对象输出下标开始值为2
>>> e2=enumerate(l,2)
>>> #将enumerate对象转为元组tuple
>>> tuple(e2)
((2, 'a'), (3, 'b'))
>>> #遍历enumerate对象中的元素
>>> for i in enumerate(l):
...     print(i)
...
(0, 'a')
(1, 'b')
>>> #遍历enumerate对象元素的下标和值
>>> for i,j in enumerate(l):
...     print(i,j)
...
0 a
1 b
>>> #遍历enumerate对象,结尾使用‘ ’分隔
>>> for i,j in enumerate(l):
...     print(i,j,end=' ')
...
0 a 1 b >>>
>>> #将enumerate对象转换为字典
>>> e2=enumerate(l,1)
>>> dict(e2)
{
    
    1: 'a', 2: 'b'}
>>> #将enumerate对象转换为集合
>>> set(e2)
set()
>>> e2=enumerate(l,1)
>>> set(e2)
{
    
    (2, 'b'), (1, 'a')}
zip()

zip(iter1[,iter2[…]])

将多个迭代器(Iterator)对象(或者可迭代(Iterable)对象)中的元素压缩到一起,返回一个zip对象

将多个迭代器(Iterator)对象(或者可迭代(Iterable)对象)中的元素压缩到一起,返回一个zip对象

>>> l1=['a','b','c','d']
>>> l2=['A','B','C','D']
>>> #压缩l1和l2
>>> z1=zip(l1,l2)
>>> #转换为list
>>> list(z1)
[('a', 'A'), ('b', 'B'), ('c', 'C'), ('d', 'D')]
>>> l3=[1,2,3,4]
>>> #压缩l1,l2,l3并转为list
>>> z2=zip(l1,l2,l3)
>>> list(z2)
[('a', 'A', 1), ('b', 'B', 2), ('c', 'C', 3), ('d', 'D', 4)]
>>> l4=['一','二']
>>> #压缩l1和l4,不同长短时,匹配完最短的结束
>>> z3=zip(l1,l4)
>>> list(z3)
[('a', '一'), ('b', '二')]
>>> #只压缩一个迭代对象时
>>> z4=zip(l1)
>>> list(z4)
[('a',), ('b',), ('c',), ('d',)]
>>> #可见,将l1中的每个值,都转成了truple
>>> #只压缩一个迭代器对象时
>>> z5=zip(enumerate(l1))
>>> list(z5)
[((0, 'a'),), ((1, 'b'),), ((2, 'c'),), ((3, 'd'),)]
>>>
map()

map(func,*iterables)

把一个函数func依次映射到可迭代(Iterable)对象的每个元素上,返回一个map对象。

map对象既是一个可迭代(Iterable)对象也是一个迭代器(Iterator)对象。

>>> l=[1,2,3,4,5]
>>> #将l中的值,转为float类型
>>> l1=map(float,l)
>>> #此时将迭代器对象转为list
>>> list(l1)
[1.0, 2.0, 3.0, 4.0, 5.0]
>>> #将l中的值转为str类型
>>> list(map(str,l))
['1', '2', '3', '4', '5']
>>> #自定义函数,并融合map使用
>>> def cc(x):
...     return x*8
...
>>> list(map(cc,l))
[8, 16, 24, 32, 40]
>>> #使用lambda函数
>>> list(map(lambda x,y:x**2+y**2,[1,2],(2,3)))
[5, 13]
>>>
fiter()

filter(function or None,iterable)

1、function:iterable的元素作为入参传入函数,并使函数返回True时,保留当前元素
2、None,函数为None,则iterable中元素等价于True的元素保留。
>>> l=[1,2,3,'',True,'1','2',[],[1]]
>>> l
[1, 2, 3, '', True, '1', '2', [], [1]]
>>> #筛选出l中所有等价于True的元素
>>> list(filter(None,l))
[1, 2, 3, True, '1', '2', [1]]
>>> #筛选出所有数字
>>> def int_ok(x):
...     return isinstance(x,int)
...
>>> list(filter(int_ok,l))
[1, 2, 3, True]
>>> isinstance(True,int)
True
>>> #使用lambda函数
>>> list(filter(lambda x:isinstance(x,int),l))
[1, 2, 3, True]
>>> #预习:使用列表推导式也可以实现筛选
>>> [x for x in l if isinstance(x,int)]
[1, 2, 3, True]
>>>

猜你喜欢

转载自blog.csdn.net/qq_39962271/article/details/128721303
4.4