""" zip(iter1 [,iter2 [...]]) --> zip object Return a zip object whose .__next__() method returns a tuple where the i-th element comes from the i-th iterable argument. The .__next__() method continues until the shortest iterable in the argument sequence is exhausted and then it raises StopIteration. """ # 返回一个zip对象,该对象的`.__next__()`方法返回一个元组,第i个元素来自第i个迭代参数,`.__next__ ()`方法一直持续到参数序列中最短的可迭代值已耗尽,而后引起StopIteration
zip()函数用于将可迭代的对象做为参数,将对象中对应的元素打包成一个个元组,而后返回由这些元组组成的列表.若是各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同。python
传入参数:元组、列表、字典等迭代器函数
当zip()函数只有一个参数时3d
zip(iterable)
从iterable中依次取一个元组,组成一个元组。code
# 元素个数相同 a = [1, 1, 1] b = [2, 2, 2] c = [3, 3, 3, 4] print(list(zip(a, b, c))) # [(1, 2, 3), (1, 2, 3), (1, 2, 3)] # 元素个数不一样 a = [1] b = [2, 2] c = [3, 3, 3, 4] print(list(zip(a, b, c))) # [(1, 2, 3)] # 单个元素 lst = [1, 2, 3] print(list(zip(lst))) # [(1,), (2,), (3,)]
zip 方法在 Python 2 和 Python 3 中的不一样:在 Python 3.x 中为了减小内存,zip() 返回的是一个对象。如需展现列表,需手动 list() 转换。对象
利用*号操做符,能够将元组解压为列表blog
tup = ([1, 2], [2, 3], [3, 4], [4, 5]) print(list(zip(*tup))) # [(1, 2, 3, 4), (2, 3, 4, 5)]
上面的例为数字,若是为字符串呢?ip
name = ['wbw', 'jiumo', 'cc'] print(list(zip(*name))) # [('w', 'j', 'c'), ('b', 'i', 'c')]
""" filter(function or None, iterable) --> filter object Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true. """ # 返回一个迭代器,该迭代器生成用于哪一个函数(项)的可迭代项是真的。若是函数为None,则返回为true的项。
filter()函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件的元素组成的新列表。该函数接受两个参数,第一个为函数,第二个为序列,序列的每一个元素做为参数传递给函数进行判断,而后返回True或False。最后将返回True的元素放到新的列表中。内存
filter(function, iterable) # functon -- 判断函数 # iterable -- 可迭代对象 # 返回列表
def is_odd(n): return n % 2 == 0 lst = range(1, 11) num = filter(is_odd, lst) print(list(num)) # [2, 4, 6, 8, 10] print(type(num)) # <class 'filter'>
""" 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. """ # 建立一个迭代器,使用来自的参数计算函数的每一个迭代器。当最短的迭代器耗尽时中止。
map()会根据提供的函数对指定序列作映射。element
第一个参数function
以参数序列中的每个元素调用function
函数,返回包含每次function
函数返回值的新列表。字符串
当seq只有一个时,将函数func做用于这个seq的每一个元素上,并获得一个新的seq。
当seq多与一个时,map能够并行(注意是并行)地对每一个seq执行如下过程。
map(function, iterable, ...) # function -- 函数 # iterable -- 一个或多个序列
def square(x): return x ** 2 lst = [1, 2, 3, 4] num = map(square, lst) print(list(num)) print(type(num))
使用匿名函数呢?
listx = [1, 2, 3, 4, 5] listy = [2, 3, 4, 5] listz = [100, 100, 100, 100] list_result = map(lambda x, y, z: x ** 2 + y + z, listx, listy, listz) print(list(list_result))