1. 程式人生 > >python zip lambda map filter

python zip lambda map filter

轉自:https://morvanzhou.github.io/tutorials/python-basic/basic/13-03-zip-lambda-map/

原創作者:莫煩

zip 

zip函式接受任意多個(包括0個和1個)序列作為引數,合併後返回一個tuple列表,請看示例:

a=[1,2,3]
b=[4,5,6]
ab=zip(a,b)
print(list(ab))  #需要加list來視覺化這個功能
"""
[(1, 4), (2, 5), (3, 6)]
"""

zip 中的運算

a=[1,2,3]
b=[4,5,6]
ab=zip(a,b)
print(list(ab))
for i,j in zip(a,b):
     print(i/2,j*2)
"""
0.5 8
1.0 10
1.5 12
"""

lambda 

lambda定義一個簡單的函式,實現簡化程式碼的功能,看程式碼會更好理解。

fun = lambda x,y : x+y, 冒號前的x,y為自變數,冒號後x+y為具體運算。


fun= lambda x,y:x+y
x=int(input('x='))    #這裡要定義int整數,否則會預設為字串
y=int(input('y='))
print(fun(x,y))

"""
x=6
y=6
12
"""


def build_quadratic_function(a,b,c):
    return lambda x: a*x**2 + b*x + c

f = build_quadratic_function(2,3,-5)
print(f(0)) #-5
print(f(1)) #0

map 

map是把函式和引數繫結在一起。

>> def fun(x,y):
	return (x+y)
>>> list(map(fun,[1],[2]))
"""
[3]
"""
>>> list(map(fun,[1,2],[3,4]))
"""
[4,6]
"""

import  math
def area(r):
    return math.pi * (r**2)

radii = [2,5,7.1,0.3,10]
areas = list(map(area,radii))
print(areas)
# [12.566370614359172, 78.53981633974483, 158.36768566746147, 0.2827433388230814, 314.1592653589793]

filter

import statistics
data = [1.3,2.7,0.8,4.1,4.3,-0.1]
avg = statistics.mean(data)

print(list(filter(lambda  x:x > avg,data)))
# [2.7, 4.1, 4.3]


# Remove missing data
countries = ["","Argentina","","Brazil","Chile",""]
print(list(filter(None,countries)))
# ['Argentina', 'Brazil', 'Chile']
# "",0,0.0,0j,[],{},(),False,None 都是空

reduce

# Reduce
from functools import reduce
data = [2,3,5,7,11,13,17,19,23,29]
multiplier = lambda  x, y:x*y
print(reduce(multiplier,data))
# 6469693230