Pythonのmap()関数は、指定されたイテラブルのすべての要素に関数を適用し、マップオブジェクトを返すために使用されます。Pythonのmapオブジェクトはイテレータであり、その要素を繰り返すことができます。また、マップオブジェクトをリスト、タプルなどのシーケンスオブジェクトに変換することもできます。
Pythonのmap()関数
Pythonのmap()関数の構文は次のとおりです:
map(function, iterable, ...)
map()関数に複数のイテラブル引数を渡すことができますが、その場合、指定された関数はその数だけの引数を持たなければなりません。関数はこれらのイテラブル要素に並列に適用されます。複数のイテラブル引数を持つ場合、最も短いイテラブルが exhausted されると、マップイテレータは停止します。
Python map()の例
map()関数とともに使用する関数を書いてみましょう。
def to_upper_case(s):
return str(s).upper()
これは、入力オブジェクトの大文字の文字列表現を返す単純な関数です。また、イテレータ要素を印刷するユーティリティ関数を定義しています。この関数は、すべてのコードスニペットで白いスペースでイテレータ要素を印刷し、再利用されます。
def print_iterator(it):
for x in it:
print(x, end=' ')
print('') # for new line
map()関数の例を異なる種類の反復可能オブジェクトで見てみましょう。
文字列を使用したPythonのmap()
# 文字列を使用したmap()
map_iterator = map(to_upper_case, 'abc')
print(type(map_iterator))
print_iterator(map_iterator)
出力:
<class 'map'>
A B C
タプルを使用したPythonのmap()
# タプルを使用したmap()
map_iterator = map(to_upper_case, (1, 'a', 'abc'))
print_iterator(map_iterator)
出力:
1 A ABC
リストを使用したPythonのmap()
map_iterator = map(to_upper_case, ['x', 'a', 'abc'])
print_iterator(map_iterator)
出力:
X A ABC
mapをリスト、タプル、セットに変換する
mapオブジェクトは反復可能なので、リスト、タプル、セットなどのファクトリーメソッドの引数として渡すことができます。
map_iterator = map(to_upper_case, ['a', 'b', 'c'])
my_list = list(map_iterator)
print(my_list)
map_iterator = map(to_upper_case, ['a', 'b', 'c'])
my_set = set(map_iterator)
print(my_set)
map_iterator = map(to_upper_case, ['a', 'b', 'c'])
my_tuple = tuple(map_iterator)
print(my_tuple)
出力:
['A', 'B', 'C']
{'C', 'B', 'A'}
('A', 'B', 'C')
Pythonのmap()とラムダ
私たちは再利用したくない場合、lambda関数をmap()と組み合わせることができます。これは、関数が小さく新しい関数を定義したくない場合に便利です。
list_numbers = [1, 2, 3, 4]
map_iterator = map(lambda x: x * 2, list_numbers)
print_iterator(map_iterator)
出力:
2 4 6 8
Python map() 複数の引数
map()関数を複数の反復可能な引数とともに使用する例を見てみましょう。
# 複数の反復可能な引数を使用したmap()
list_numbers = [1, 2, 3, 4]
tuple_numbers = (5, 6, 7, 8)
map_iterator = map(lambda x, y: x * y, list_numbers, tuple_numbers)
print_iterator(map_iterator)
出力: 5 12 21 32
関数が2つの引数を持っていることに注意してください。出力されるmapイテレータは、この関数を2つの反復可能な要素に並行して適用した結果です。異なるサイズの反復可能な要素の場合に何が起こるか見てみましょう。
# 異なるサイズの反復可能な引数を使用したmap()
list_numbers = [1, 2, 3, 4]
tuple_numbers = (5, 6, 7, 8, 9, 10)
map_iterator = map(lambda x, y: x * y, list_numbers, tuple_numbers)
print_iterator(map_iterator)
map_iterator = map(lambda x, y: x * y, tuple_numbers, list_numbers)
print_iterator(map_iterator)
出力:
5 12 21 32
5 12 21 32
引数のサイズが異なる場合、map関数はいずれかが使い果たされるまで要素に適用されます。
Python map() 関数とNoneの場合
関数をNoneとして渡した場合に何が起こるか見てみましょう。
map_iterator = map(None, 'abc')
print(map_iterator)
for x in map_iterator:
print(x)
出力:
Traceback (most recent call last):
File "/Users/pankaj/Documents/github/journaldev/Python-3/basic_examples/python_map_example.py", line 3, in <module>
for x in map_iterator:
TypeError: 'NoneType' object is not callable
あなたは私たちのGitHubリポジトリから完全なPythonスクリプトやさらに多くのPythonの例をチェックアウトできます。
参照:公式ドキュメント
Source:
https://www.digitalocean.com/community/tutorials/python-map-function