python+map()関数の詳細

10989 ワード

python+map()関数の詳細
前置きの簡単な問題
xを入力して関数値f 1を求める
list_x = [1,2,3,4,5,6,7,8]
a = 1
def f1(x):
    return a*x*x

第1の方法:c言語c++思想
#        c   c++  
y = []
for i in range(len(list_x)):
    y.append(f1(list_x[i]))
print(y)

しゅつりょく
[1, 4, 9, 16, 25, 36, 49, 64]
第2の方法:python思想
#         python   
list_y = []
for x in list_x:
    list_y.append(f1(x))
print(list_y)

しゅつりょく
[1, 4, 9, 16, 25, 36, 49, 64]
3つ目の方法:python map関数
#        python map  
r = map(f1,list_x)
print(list(r))

しゅつりょく
[1, 4, 9, 16, 25, 36, 49, 64]
第4の方法:python map関数のステップlambda匿名関数はdefを必要としない
#        python   map+     lambda
r = map(lambda x:x*x , list_x)
print(list(r))

しゅつりょく
[1, 4, 9, 16, 25, 36, 49, 64]
mapのステップアップ
mapの入力要素のリストの関係は一つ一つ対応している
#map                   

test_x = [1,2,3,4,5,6,7,8,9]  #9   
test_y = [1,2,3,4,5,6]        #6   
test_z = [1,2,3]              #3   
r = map(lambda x,y,z:x+y+z,test_x,test_y,test_z)
print(list(r))

しゅつりょく
[3, 6, 9]
mapの判断文
#map        
r = map(lambda n:n>5,range(10))
print(list(r))

しゅつりょく
[False, False, False, False, False, False, True, True, True, True]
mapの出力判定文の要素
#        filter  
r = filter(lambda n:n>5,range(10))
print(list(r))


しゅつりょく
[6, 7, 8, 9]
mapの適用:正しい人名フォーマットに変更
#map                  

name = ['haRRY','JoHn','saaaa']
print(name)
def translation(x):
    Name = x[0:1].upper()+x[1:].lower()
    return Name
r = map(translation,name)
print(list(r))

しゅつりょく
[‘haRRY’, ‘JoHn’, ‘saaaa’] [‘Harry’, ‘John’, ‘Saaaa’]