python関数lambda()、filter()、map()、reduce()
1368 ワード
(1)lambda
Lambdaはpythonで匿名関数を作成し、構文フォーマットは次のとおりです.
(2)map()
map(function,sequence):sequenceのitemに対してfunction(item)を順次実行し、実行結果がリストを構成して返されるのを参照してください.例を次に示します.
(3)reduce()
reduce(function,sequence,starting_value):sequenceのitemに対してfunctionを繰り返し呼び出し、starting_がある場合valueは、初期値として呼び出すこともでき、例えばListの合計を求めるために使用することができる.
(4)filter()
filter(function,sequence):sequenceのitemに対してfunction(item)を順次実行し、実行結果がTrueのitemをリスト/string/Tople(sequenceのタイプに依存)として返します.例は以下の通り
Lambdaはpythonで匿名関数を作成し、構文フォーマットは次のとおりです.
lambda [arg1[, arg2, ... argN]]: expression
使用例:#
fun = lambda x,y:x+y
print fun(1,2)
# :
3
#
print (lambda x,y:x+y)(1,2)
# :
3
# :
def func_1(x, y):
return x + y
print func_1(1, 2)
(2)map()
map(function,sequence):sequenceのitemに対してfunction(item)を順次実行し、実行結果がリストを構成して返されるのを参照してください.例を次に示します.
def cube(x):
return x*x*x
print map(cube, range(1, 11))
# :
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
(3)reduce()
reduce(function,sequence,starting_value):sequenceのitemに対してfunctionを繰り返し呼び出し、starting_がある場合valueは、初期値として呼び出すこともでき、例えばListの合計を求めるために使用することができる.
def add(x,y):
return x + y
print reduce(add, range(1, 11))
print reduce(add, range(1, 11), 20)
# :
55 #1+2+3+4+5+6+7+8+9+10
75 #1+2+3+4+5+6+7+8+9+10+20
(4)filter()
filter(function,sequence):sequenceのitemに対してfunction(item)を順次実行し、実行結果がTrueのitemをリスト/string/Tople(sequenceのタイプに依存)として返します.例は以下の通り
# 1
def f(x):
return x % 2 != 0 and x % 3 != 0
print filter(f, range(2, 25))
# :
[5, 7, 11, 13, 17, 19, 23]
# 2
def f(x):
return x != 'a'
print filter(f, "abcdef")
# :
'bcdef'