Python - map
公開日:2019-03-12 更新日:2019-05-29
[Python]
1. 概要
map の使い方です。
map は、リストなどの各要素に対して、関数を適用したい場合に使います。
戻り値はイテレーターとなります。元のリストなどには影響はありません。
また、map() 実行時には、まだ関数は適用されません。for などで要素を取り出す際に実行されます。
map は、リストなどの各要素に対して、関数を適用したい場合に使います。
戻り値はイテレーターとなります。元のリストなどには影響はありません。
また、map() 実行時には、まだ関数は適用されません。for などで要素を取り出す際に実行されます。
map(適用する関数, リストなど)
2.1 サンプル
map の動作確認のためのサンプルです。
def inc(value):
return value + 1
lst = [1,2,3,4,5]
m = map(inc, lst)
for item in m:
print(item)
print(lst)
2
3
4
5
6
[1, 2, 3, 4, 5]
2.2 ラムダ式を使ったサンプル
for item in map(lambda v: v * 2, [1,2,3,4,5]):
print(item)
2
4
6
8
10
3. 遅延評価の確認
map() 実行時には関数が適用されないことを確認します。
def inc(value):
print("inc()処理中")
return value + 1
lst = [1,2,3,4,5]
m = map(inc, lst)
print("この段階では、まだ関数は実行されません。")
print("-----")
for item in m:
print(item)
print("-----")
print(lst)
print(type(m))
この段階では、まだ関数は実行されません。
-----
inc()処理中
2
inc()処理中
3
inc()処理中
4
inc()処理中
5
inc()処理中
6
-----
[1, 2, 3, 4, 5]
<class 'map'>