Pythonでの入力データ読み込み方法(初学者向け)
投稿者:CarpDay.icon
1. 整数の読み込み
実数なら int を floatに変更すれば,大抵OK
(1) 1行に入力された1つの整数を変数に格納.データ例: "5"
code: python
n = int(input()) 
(2) 1行に空白区切りで並べられた2つの整数を2つの変数に格納.データ例:"3 5"
code: python
a, b = map(int, input().split())
内包表記を使ってもよい.
code: python
a, b = int(e) for e in input().split()
あんまりないとは思うけど,区切り文字が空白以外(例えばコンマ)なら,splitの中に区切り文字を指定する.
code: pyton
a, b = map(int, input().split(","))
(3) 1行に空白区切りで並べられた2つ以上の整数を格納.データ例: "3 5 8 13"
2個のときと同じ.左辺に値を代入したい数だけ変数を用意する.
code: python
a, b, c, d = map(int, input().split()) # a -> 3, d -> 13
または,リストとして受け取る.
code: python
a = list(map(int, input().split())) # a0 -> 3, a3 -> 13
最初の例の右辺で,listが付いていても問題ないです.
これも内包表記にしてもよい.
code: python
a, b, c, d = int(c) for c in input().split() # 内包表記の中のcと外のcで名前が同じでも問題ない(推奨しない)
code:python
a = int(c) for c in input().split()
(4) 連続する n 行に1つずつ存在する整数をリストに格納.
データ例:(この場合,n = 3)
code:txt
3
5
8
code: python
a = []
for _ in range(n):
a.append(int(input())
内包表記の方がシンプル.
code: python
a = int(input()) for _ in range(n) # a -> 3, 5, 8
(5) 連続する n 行に複数の整数.2次元リストに格納.
データ例:(この場合,n = 2)
code:txt
1 2 3
4 5 6
code: python
a = []
for _ in range(n):
a.append(list(map(int, input().split())))
これも内包表記の方がシンプル.
code: python
a = list(map(int, input().split())) for _ in range(n) # a -> 1, 2, 3], [4, 5, 6, a01 -> 2
1行に存在する整数の個数を気にしなくてよい点が秀逸.
二重の内包表記も可能
code: python
a = [int(c) for c in input().split() for _ in range(n)]
2. 文字列の読み込み
(1) 1行そのまま読み込み文字列に格納.データ例:"This is a pen."
code: python
s = input() # s -> "This is a pen."
空白も文字列の一部として読み込まれる
(2) 1行に空白で区切られた複数の文字列をリストに格納.データ例:"This is a pen."
code: python
words = input().split() # words -> "This", "is", "a", "pen."
空白が区切り文字として使われている例.
(3) 1行に入力された文字列を1文字ずつ区切ってリストに格納.データ列:pen
code: python
c_list = list(input()) # c_list -> "p", "e", "n"
(4) 連続する n 行に入力された文字列をリストに格納.
データ例:(この場合,n = 3)
code:txt
.#.
&.*
$..
code: python
board = input() for _ in range(n) # board -> "&.*", "$..", board01 -> '#', board20 -> '&'
2次元平面上の地図を探索するような問題でよく見られます.
文字列は変更不可なので,board[0][1]='X'のような書き換えはできません.書き換えしたいときは,次の(5).
(5) 連続するn行に入力された文字列を1文字ずつ区切って2次元リストとして格納.
データ例:(4)と同じ.
code: python
board = list(input()) for _ in range(n)
# board -> ["#", ".", ".", "*", "$", ".", "."] board01 -> "#", board20 -> "$"
(4)の文字列をリストに変換.この場合は,board[0][1] = 'X'のような書き換えは可能.ただし,実行速度は(4)より遅い.
後のプログラムで文字を書き換えるかどうかで使い分ける.
3. 整数と文字列の混在
1行に整数と文字列が混在すること問題もまれに存在します.
例えば,A~C組で未回答の生徒数と生徒名が3行に渡り入力されていて,キーがクラス名,値が生徒名の辞書に格納するケースは次のようになります.
データ例:(クラス数 n = 3)
code:txt
A 2 Aoki Ota
B 1 Kato
C 3 Sakura Sumida Sone
code: python
d = dict()
for _ in range(n):
s = input().split() # 1行目の場合 s = "A", "2", "Aoki", "Ota"
if int(s1) > 0:
d[s0] = s2: # 1行目の場合 d"A" = "Aoki", "Ota"
else:
d[s0] = []
Ex. 高速な入力
基本的に(Pythonに限らず)どんな言語も入出力は遅い.
普段はあんまり気にしなくて良いけど,TLE:2000msecで2100msかかり,あとちょっと高速化したい時に入力を高速化すればACということも稀にあるので頭の片隅に置いておく.
高速化できるのは,複数行(e.g. $ 10^6 行とか)の入力
code:python
import sys
for _ in range(10**6):
a = input() # 遅い
b = sys.stdin.readline().strip() # ちょっとだけ速い
#はじめに #Python #初心者向け