LoginSignup
0
1

More than 3 years have passed since last update.

【Python】スペース区切りのコマンドライン引数をint型でリスト化

Last updated at Posted at 2021-04-18

スペース区切りのコマンドライン引数をint型にしてリスト化する

競技プログラミングなどで割と使うことが多いので、個人的な備忘録。

入力例1
1 2 3 4 5

これをint型でリストに入れたい。

sample.py
int_list = list(int(x) for x in input().split())

※頂いたコメントを参考にmapを使った方法を追記します。↓

sample.py
int_list = [*map(int, input().split())]
sample.py
int_list = list(map(int, input().split()))

出力結果↓

sampleの結果
print(int_list)
# [1, 2, 3, 4, 5]

おまけ

文字列のままリストに入れる

sample1.py
str_list = input().split()

リストにしないでint型で変数にアンパック

sample2.py
a, b, c, d, e = (int(x) for x in input().split())

※こちらもmapを使った方法を追記↓

sample3.py
a, b, c, d, e = map(int, input().split())
0
1
2

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
1