python map iter

map函数可以对迭代变量里面的每一个元素进行相同的操作。

>>> help(map)

Help on class map in module builtins:



class map(object)

 |  map(func, *iterables) --> map object
 |  
 |  Make an iterator that computes the function using arguments from
 |  each of the iterables.  Stops when the shortest iterable is exhausted.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |  
 |  __iter__(...)
 |      x.__iter__() <==> iter(x)
 |  
 |  __next__(...)
 |      x.__next__() <==> next(x)
 |  
 |  __reduce__(...)
 |      Return state information for pickling.
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T




>>> def  Myfunc(a):
return (a**2)


>>> bb=map(Myfunc,[1,2,3,4])
>>> for i in bb:
print (i)

1

4

9

16

>>> 


 iterator是迭代器的意思,它的作用是一次产生一个数据,并记住当前的状态,以便产生下一个数据。相比list和tuple来说,会占用更小的内存,尤其是当数据量比较大的时候。可以通过__next__()函数来获得下一项数据,不能像list和tuple通过索引来获取值。

>>> a=[1,2,3,4]
>>> aa=iter(a)
>>> aa
<list_iterator object at 0x01ED7F90>
>>> aa.__next__()
1
>>> aa.__next__()
2
>>> aa.__next__()
3
>>> aa.__next__()
4
>>> aa.__next__()
Traceback (most recent call last):
  File "<pyshell#145>", line 1, in <module>
    aa.__next__()
StopIteration

>>> for i in aa:
print(i)


为什么打印出来是空的呢?这是因为迭代器只读取一次,读完就没有了,所以如果后面再跟一个for循环打印其数据,打印出来的就为空。但是生成器之后直接用for循环打印,就可以将数据项打印出来。__next__()迭代完成后会自动抛出 StopIteration 异常,表示迭代完成。在 for 循环里,无需处理 StopIteration 异常,循环会正常结束。
>>> aa=iter(a)
>>> for i in aa:
print(i)



1
2
3
4

当数据量很大的时候就会节省很多内存,文件操作就是采用迭代器。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值