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
当数据量很大的时候就会节省很多内存,文件操作就是采用迭代器。