LoginSignup
134

More than 3 years have passed since last update.

【Python】競技プログラミング 基本入力まとめ

Last updated at Posted at 2019-05-17

はじめに

タイトルの通り,競技プログラミング向けのPythonの基本入力集です.
なお,文字列の入力がうまくいかないときはintstrにすることでも対応できます.

実は

Pythonのinput() は入力速度がそこまで早くないらしいので,入力が多い問題では以下の一行を文頭に書いておくとTLEを防げるかもしれません. (AtCoderのPython3.4.3で動作確認済)

Python
from sys import stdin
input = stdin.readline

【2019/11/27追記】 上記の二行だとたまに改行文字まで入力されてしまう場合があるようです。ご注意ください.

Python
x = input().rstrip()

【2020/05/06追記】 上記のようにinput()の後に.rstrip()を入れることで回避できます.

【1行】1文字

input()はstr型で入力を受け取ります.

入力
abc
Python
s = input()  # sはstr型

【1行】1数字

入力
10
Python
n = int(input())  # nはint型

【1行】n文字

2個以上の半角スペースで区切られた入力ではmap関数やsplit()を使いましょう.

入力
abc def ghi
Python
a,b,c = input().split()  #3個の文字列の入力を受け取る

リストに格納したい場合.

Python
str_list = list(input().split())  # n個の文字列がリストに格納される

【1行】n数字

入力
1 2 3
Python
a,b,c = map(int, input().split())  # 3個の数字の入力を受け取る
print(a,b,c)                       # 出力を確認

リストに格納したい場合.

Python
num_list = list(map(int, input().split()))  # n個の数字がリストに格納される

【n行】1文字

最初にn回という入力回数が与えられ,その後入力があるような場合です.

入力
3
aa
a
aaa
Python
n = int(input())  # nは入力回数
str_list = [input() for _ in range(n)]
print(str_list)   # 出力を確認
出力
['aa', 'a', 'aaa']

【n行】1数字

入力
4
2
3
4
5
Python
n = int(input())  # nは入力回数
num_list = [int(input()) for _ in range(n)]
print(num_list)   # 出力を確認
出力
[2, 3, 4, 5]

【n行】n文字

入力回数がn回と分かっている場合,for文とappend()で二次元リストとして入力を格納できます.

入力
3
aaa b cc
d ee fff
gg hhh i
Python
n = int(input())  # nは入力回数
str_list = []
for i in range(n):
    str_list.append(list(input().split()))
print(str_list)

以下は内包表記を使った場合.楽&早.

Python
n = int(input())  # nは入力回数
str_list = [list(input().split()) for _ in range(n)]
print(str_list)
出力
[['aaa', 'b', 'cc'], ['d', 'ee', 'fff'], ['gg', 'hhh', 'i']]

【n行】n数字

入力
3
2 1 3
3 1 2 3
2 3 2
Python
n = int(input())  # nは入力回数
num_list = []
for i in range(n):
    num_list.append(list(map(int,input().split())))
print(num_list)

同様に内包表記を使った場合.

Python
n = int(input())  # nは入力回数
num_list = [list(map(int, input().split())) for _ in range(n)]
print(num_list)
出力
[[2, 1, 3], [3, 1, 2, 3], [2, 3, 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
134