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()函數用於將可迭代的對象做爲參數,將對象中對應的元素打包成一個個元組,而後返回由這些元組組成的列表.若是各個迭代器的元素個數不一致,則返回列表長度與最短的對象相同。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()

"""
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()會根據提供的函數對指定序列作映射。element

第一個參數function以參數序列中的每個元素調用function函數,返回包含每次function函數返回值的新列表。字符串

  1. 當seq只有一個時,將函數func做用於這個seq的每一個元素上,並獲得一個新的seq。

  2. 當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))
相關文章
相關標籤/搜索