10
17

More than 3 years have passed since last update.

Python 標準入力まとめ

Last updated at Posted at 2019-07-05

基本的な入力 (1区切りの文字列の入力)

区切りのない連続した文字列の入力。
入力した文字列の型を任意に指定でき、指定しない場合はstr型になる。
以下で二通りの標準入力の仕方を紹介する。

inputを使う場合

通常はこちらで問題ないです。多くの入力を扱う必要があり少しでも早くしたい方は以下をもう一方を使うほうがいいかもしれません。

input_1.py
a = input()
b = str(input())
c = int(input())
d = float(input())

print(a, type(a)) # 入力:1234 出力:1234 <class 'str'>
print(b, type(b)) # 入力:1234 出力:1234 <class 'str'>
print(c, type(c)) # 入力:1234 出力:1234 <class 'int'>
print(d, type(d)) # 入力:1234 出力:1234.0 <class 'float'>

sys.stdin.readlineを使う場合

input()とほぼ同様に使え、入力数が大きくなるとこちらのほうが有意に早くなる。

readline_1.py
import sys
input = sys.stdin.readline

N = int(input())
A = list(map(int,input().split()))

print(N) # 入力:3 出力:3
print(A) # 入力:1 3 2 出力:[1, 3, 2]

その他のpythonの処理速度を早くする工夫併せてこちらを参照ください。
https://www.kumilog.net/entry/python-speed-comp

行の配列(横一列の複数の入力)

区切りのある横一列の複数の文字列を任意の型に指定できる。
区切りの入れ方はsplitで指定する。

input_2.py
x, y = map(int, input().split())           # 入力:1 2
a, b = map(int, input().split(','))        # 入力:1, 2
c, d, e = map(str, input().split())        # 入力:1 2 3
A = [int(i) for i in input().split()]      # 入力:1 2 3 4 5 6
B = list(str(i) for i in input().split())  # 入力:1 2 3 4 5 6
C = list(map(int, input().split()))        # 入力:1 2 3 4 5 6

print(x,y)                                 # 1 2
print(a,b)                                 # 1 2
print(c, d, e)                             # 1 2 3
print(A)                                   # [1, 2, 3, 4, 5, 6]
print(B)                                   # [1, 2, 3, 4, 5, 6]
print(C)                                   # [1, 2, 3, 4, 5, 6]

列の配列(縦一列の複数の入力)

縦一列に入力された文字列を一つのリストで管理する。

input_3.py
X = [int(input()) for i in range(5)]
# 入力: 
# 1
# 2
# 3
# 4
# 5
print(X) # [1, 2, 3, 4, 5]

二次元配列(縦横複数行の入力)

縦横複数列の入力を列ごとに二次元配列で管理する。

input_3.py
N = int(input()) # 入力: 5
Array = [list(map(str, input().split())) for _ in range(N)]
# 入力:
# -7 -10 U
# 7 -6 U
# -8 7 D
# -3 3 D
# 0 -6 R
print(Array) # [['-7', '-10', 'U'], ['7', '-6', 'U'], ['-8', '7', 'D'], ['-3', '3', 'D'], ['0', '-6', 'R']]

参考記事

10
17
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
10
17