0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python】map関数

Posted at

map関数

map関数は、指定した関数をイテラブル(リストやタプルなど)の各要素に適用し、その結果を返すために使用されます。以下に、map関数の詳細といくつかの例を示します。

基本的な使い方

map関数は、次のように使用します:

map(function, iterable, *iterables)

function: 各要素に適用する関数。
iterable: 処理対象のイテラブル(リストやタプルなど)。
iterables: 追加のイテラブル(オプション)。複数のイテラブルを同時に処理することができます。

例1: 単一のイテラブル

numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared)  # 出力: [1, 4, 9, 16, 25]

例2: 複数のイテラブル

list1 = [1, 2, 3]
list2 = [4, 5, 6]
summed = list(map(lambda x, y: x + y, list1, list2))
print(summed)  # 出力: [5, 7, 9]

例3: itertools.starmapとの違い

mapは、関数が単一の引数を取る場合に便利ですが、引数がタプルとして与えられている場合は、itertools.starmapを使うと便利です。

from itertools import starmap

pairs = [(1, 2), (3, 4), (5, 6)]
summed = list(starmap(lambda x, y: x + y, pairs))
print(summed)  # 出力: [3, 7, 11]

注意点

mapはイテレータを返すため、リストとして結果を得たい場合はlist()で囲む必要があります。
Python 3では、mapの結果は遅延評価されるため、必要なときに計算されます。
map関数は、データの変換や処理を簡潔に行うための強力なツールです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?