0
0

More than 1 year has passed since last update.

【Python】map()・filter()関数の計算結果をprint()関数で出力する方法

Posted at

初めに

pythonの勉強中にmap()関数の動作確認のため結果をprint()関数で結果を出力しようとしたら、map型のオブジェクトが出力されてしまい計算結果がわからなかったので、結果を出力する方法を調べました。filter()関数の場合も同様にfilter型オブジェクトになるので、同じ方法で出力可能です。

※間違っている情報等・不足している内容あればコメントいただけると幸いです。

環境

python: 3.10.4
OS: Windows 10 Home

コード

以下の二つの方法のどちらかを使うことで、結果を出力できました

  1. *(アスタリスク)を使ってアンパックする

  2. list()を使ってリストに変換する

サンプルのコードは以下になります。

people = [("Abel", 20), ("Bob", 21), ("Cait", 16), ('Dave', 18), ('Eva', 19)]


def get_age(person):
    return person[1]

# 方法1:*(アスタリスク)を使ってアンパックする
ages = map(get_age, people)
print(ages)  # そのままだと<map object at 0x00000132C6A878E0> と出力されてしまう
print(*ages)  # 20 21 16 18 19 とアンパックされて出力される

# 方法2:list()を使ってリストに変換する
ages2 = map(get_age, people)
print(ages2)  # そのままだと<map object at 0x00000132C6A878E0> と出力されてしまう
print(list(ages2))  # [20, 21, 16, 18, 19] とリストで出力される

参考にした記事

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