0
0

More than 3 years have passed since last update.

mapはよくわからないけど、list(map(int, input().split()))だけ理解する

Posted at

プロローグ

mapはよくわからないけど、よく目にするlist(map(int, input().split()))だけ理解するゾ

list(map(int, input().split()))の動き

とりあえず動かしてみるとわかりますが、複数の数字の入力から数値のリストを作成します。

>>> list(map(int, input().split()))
1 2 3
[1, 2, 3]
>>>

分解して理解する

input().split()について

input().split()はインプットの文字列を分割します。

>>> input().split()
ホップ ステップ ジャンプ
['ホップ', 'ステップ', 'ジャンプ']

map(int, input().split())について

mapは第一引数を第二引数に適用して、mapオブジェクトを返すらしい。
なので、戻りは、よくわからないmapオブジェクト

>>> map(int, input().split())
ホップ ステップ ジャンプ
<map object at 0x00000144D6B62388>

list(map(int, input().split()))について

mapオブジェクトで得たものをlistに変換しています。

>>> list(map(int, input().split()))
ホップ ステップ ジャンプ
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'ホップ'

当然、intを得てリストを返すつもりなのでエラーとなっている。
数値を与えると、冒頭の通り、リストを得られる

>>> list(map(int, input().split()))
99 98 97 96 95
[99, 98, 97, 96, 95]

エピローグ

mapはよくわかってないけど、list(map(int, input().split()))の動きだけ理解できた

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