首页 新闻 会员 周边

iterable和iterator

0
[已关闭问题] 关闭于 2026-07-08 15:06

iterable是可迭代对象,能被迭代的,有__iter__方法

iterator是迭代器,有__iter__同时该方法返回self自身,有__next__方法

看看help(zip),zip返回的元组对象,元组里面第i个元素,来自于你传入的zip函数的第i个可迭代的参数,

zip(iter1 [,iter2 [...]]) ->zip object

这里的iter1,2就是可迭代对象

list(zip([1,2,3,4],[2,1])),最短的取完结束[(1,2),(2,3)]

 

zip(iter1 [,iter2 [...]] )只是文档写法, 其实也是*iterables,没区别,和版本有关,有的版本也写*iterables

 

 

看看help(map), 

map(func,*iterable) ->map object

make an iterator that compute the function using arguments from each of the iterables

创造一个迭代器,该迭代器使用从每个可迭代对象中获取的参数来计算函数,当最短的可迭代对象被耗尽时

*iterables是可以传1个,2个,3个。。。任意数量的位置参数可迭代对象并行处理

只要这堆可迭代对象里,有任何一个(最短的可迭代对象)被取完耗尽立刻停止

传两个可迭代对象,并行处理,需要传两个参数(不能一个),然后[3,0]最短可迭代对象取完结束,所以结果是11 ,6

list(map(lambda x,y:2*x + 3*y,[1,3,5,7],[3,0]))   11,6

 

再看help(filter)

filter(function or None,iterable) ->filter objec

return an iterator yielding those items of iterable for which function(item) is true

返回一个迭代器,该迭代器只产出那些函数让function(item)为真的选项,如果传入的function为None,则直接保留那些本身为真的元素

filter(lambda x: x>3,[1,3,6,2,9]) [6,9]

 

 

再看help(functools.reduce)

reduce(function,sequence[,initial])->value(值)

function和sequence必须的,initial可选这是初始值

注意这里的sequence序列因为reduce古老函数的叫法,现在是iterable可迭代对象

apply a function of two arguments cumulatively to the items of a sequence,from left to right,so as to reduce the sequence to a single value

cumulatively /‘kju:mjeletively/ q-miu-le-ti-ve-ly 累计地,逐渐增加地

将一个将接受两个参数的函数累积地应用到序列的项中(从左到右),从而将序列压缩成当个值

reduce(lambda x,y: x+y, [1,2,3],10)  10+1+2+3=16

reduce(lambda x,y:x+y,[1,2,3])   1+2+3=6

 

 

 

 

 

 

 

 

*Tesla*的主页 *Tesla* | 老鸟四级 | 园豆:2040
提问于:2026-07-08 15:05
< >
分享
所有回答(1)
0

你会发现上面的函数接受的参数都是iterable可迭代对象

*Tesla* | 园豆:2040 (老鸟四级) | 2026-07-08 15:06

for循环隐式的得到了迭代器,​而上面的函数显示的得到了迭代器,​

 

在  for  循环内部亲眼“抓”到那个隐式的迭代器:

1. for 循环是“隐式”的:它把获取迭代器的脏活累活都藏在底层了,对使用者极其友好。你只管写 for x in data: ,Python 解释器在背后默默帮你调用 iter() 和 next() 。
2. map / filter 是“显式”的:它们不替你消费数据,而是直接把那个迭代器对象交还给你(即 return an iterator )。你拿到了这个迭代器,决定什么时候去遍历它、遍历多少。

class MyIterable:
    def __init__(self, data):
        self.data = data

    def __iter__(self):
        # 关键证据在这里:当 for 循环启动时,这行代码会执行
        print("🚨 警报!for 循环正在调用 __iter__ 获取迭代器!")
        self.index = 0
        return self  # 返回迭代器本身

    def __next__(self):
        if self.index >= len(self.data):
            raise StopIteration
        value = self.data[self.index]
        self.index += 1
        return value

# 现在,我们用 for 循环来遍历它
print("准备开始 for 循环...")
for item in MyIterable([1, 2, 3]):
    print(f"循环体拿到的元素: {item}")

 

支持(0) 反对(0) *Tesla* | 园豆:2040 (老鸟四级) | 2026-07-08 15:33
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册