Python内置函数之zip、filter、map

zip()

"""
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()函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表.如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同。

  • 传入参数:元组、列表、字典等迭代器

  • 当zip()函数只有一个参数时

    zip(iterable)从iterable中依次取一个元组,组成一个元组。

# 元素个数相同
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() 转换。

利用*号操作符,可以将元组解压为列表

tup = ([1, 2], [2, 3], [3, 4], [4, 5])
print(list(zip(*tup))) # [(1, 2, 3, 4), (2, 3, 4, 5)]

上面的例为数字,如果为字符串呢?

name = ['wbw', 'jiumo', 'cc']
print(list(zip(*name))) # [('w', 'j', 'c'), ('b', 'i', 'c')]

filter()

"""
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()

"""
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()会根据提供的函数对指定序列做映射。

第一个参数function以参数序列中的每一个元素调用function函数,返回包含每次function函数返回值的新列表。

  1. 当seq只有一个时,将函数func作用于这个seq的每个元素上,并得到一个新的seq。Python内置函数之zip、filter、map

  2. 当seq多与一个时,map可以并行(注意是并行)地对每个seq执行以下过程。Python内置函数之zip、filter、map

语法:

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))