LoginSignup
9
10

More than 3 years have passed since last update.

[Python]標準入力

Last updated at Posted at 2020-05-19

標準入力

AtCoderなどを想定した、Pythonでの標準入力方法をまとめました。

文字列

サンプルコード
S = input() #ここで標準入力
print (type(S), S)
#<class 'str'> atcoder

整数

サンプルコード
N = int(input()) #ここで標準入力
print (type(N), N) 
#<class 'int'> 20

行列

サンプルコード
R = int(input()) #行数の入力
P = [list( map( int, input().split() ) ) for i in range(R)] #2行目以降標準入力
# map(関数, 要素)
print(type(P), P)
#<class 'list'> [[1, 32], [2, 63], [1, 12]]

大量の入力

サンプルコード
import sys
import itertools
import numpy as np

read = sys.stdin.buffer.read
#標準入力から複数行取得するための関数です。 readlines() が結果を行単位で分割してリストで返すのに対して、 read() は結果をそのまま1つの文字列として取得します。
readline = sys.stdin.buffer.readline
#標準入力から1行取得するための関数です。
readlines = sys.stdin.buffer.readlines
#標準入力から複数行取得するための関数です。戻り値はリストで、入力された文字列が1行ずつ要素として格納されています。
# .bufferはbytes を返すのでさらに少しだけ速いようですが、あまり差はありません。

# 標準入力例
# 3 4 3
# 1 3 3 100
# 1 2 2 10
# 2 3 2 10

N, M, Q = map(int, readline().split())
print(N, M, Q)
# 3 4 3

# 数値のNumPy配列(N×M)として入力したい場合 npを外せばリストになる。
# 文字列はbytes型なので'b""'が付く。結合等出来ないのでread定義からbufferを外した方が良い。
# input()と併用は避ける。
A = np.array(list(map(int, read().split()))).reshape((N, M))
# 下記と同型のNumPy配列を取得

m = map(int, read().split())
#print(list(m))
# <map object at 0x7f78f13a7d30> [1, 3, 3, 100, 1, 2, 2, 10, 2, 3, 2, 10]

for a,b,c,d in zip(m,m,m,m): # 複数のイテラブルオブジェクト(リストやタプルなど)の要素をまとめる関数
  print(a,b,c,d)
# 1 3 3 100
# 1 2 2 10
# 2 3 2 10
9
10
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
9
10