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?

map関数でのエラー

Posted at

Atcoderでpythonを練習中にでたエラーについてはアウトプットのため、まとめる

問題はこちら

修正前コード

修正前コード
# mapオブジェクトをリスト化
num_list = list(map(int, input().split()))

# 1の個数をカウントして出力
print(num_list.count(1))

入力
101
出力
0

原因

input().split() は スペース区切りの入力をリストとして処理する。
しかし111 のように スペースがない場合 は、リストではなく そのまま "111" という文字列 になる。
したがって map(int, input().split()) は "111" を数値に変換しようとし、num_list = [111] となる。

つまり、111 はリスト [1, 1, 1] にはならず [111] になり、count(1) しても 0 になる。

修正後コード

修正後コード
num_list = [int(x) for x in input()]  # 文字列を1桁ずつリスト化

print(num_list.count(1))  # 1の個数をカウント

入力
101
出力
2
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?