理系大学院生の日常

理系大学院生の備忘録

Pythonでmapとラムダ式を使ってみた

今まではfor文でぶん回してたところをmapとlambdaを勉強したのでメモ。

今回は入力で与えられたリストの各要素に対して、2倍した値を出力のリストに格納する処理を様々な方法で記述。

for文での実装

# # 入力リスト
input_list = [1, 2, 3, 4, 5]
print('入力: ' + str(input_list))

def calc_double(x):
    """
    引数を2倍して返す関数
    """
    return x * 2


# # 出力用のリスト
ans_list = []

# # リスト内の一つひとつの要素に対してcalc_doubleを適用。
# # その結果を出力用のリストに追加
for l in input_list:
    ans_list.append(calc_double(l))

print('出力: ' + str(ans_list))

f:id:scootee:20210920202430p:plain


mapを使う

# # 入力リスト
input_list = [1, 2, 3, 4, 5]
print('入力: ' + str(input_list))

def calc_double(x):
    """
    引数を2倍して返す関数
    """
    return x * 2


# # 出力用のリスト
ans_list = []
ans_list = list(map(calc_double, input_list))
print('出力: ' + str(ans_list))

f:id:scootee:20210920202542p:plain

  • mapの使い方
    • map()の第1引数は適用したい関数、第2引数は対象となるリスト(タプルや集合でもOK!)
    • map()だけでは戻り値がオブジェクト?になってしまうので、リスト型でキャスト。

map+lambdaを使う

# # 入力リスト
input_list = [1, 2, 3, 4, 5]
print('入力: ' + str(input_list))

# # 出力用のリスト
ans_list = []
ans_list = list(map(lambda x: x * 2, input_list))
print('出力: ' + str(ans_list))

f:id:scootee:20210920202542p:plain

  • lambdaの使い方
    • lambda (引数): (処理), (対象となるリスト)

lambda + if文

# # 入力リスト
input_list = [1, 2, 3, 4, 5]
print('入力: ' + str(input_list))

# # 出力用のリスト
ans_list = []
ans_list = list(map(lambda x: x * 2 if x % 2 == 0 else x * (-2), input_list))
print('出力: ' + str(ans_list))

f:id:scootee:20210923140209p:plain

  • lambdaでのif文の使い方
    • lambda (引数): (処理A) if (処理Aをする条件式) else (処理B), (対象となるリスト)

結構複雑な処理も1行でできそう。


まとめ

今回は同じ処理を単純なfor文、map、lambdaを使ってやってみた。 lambdaの威力を見せつけられた結果だった。