0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

競技プログラミングの入出力メモ

Last updated at Posted at 2025-02-15

入力

1行

空白なしの文字列を受け取る

最も基本な形

# 入力
20250222
# str型の場合
print(input())

# 出力 `20250222`


# int型に変換する場合
print(int(input()))

# 出力 `20250222`

スペース区切りの文字列をリストとして受け取る

# 入力
1 2 3 4 5
# str型の場合
print(list(map(str, input().split())))

# 出力 `['1', '2', '3', '4', '5']`


# int型に変換する場合
print(list(map(int, input().split())))

# 出力 `[1, 2, 3, 4, 5]`
  • input().split() で スペース区切りで分割
  • map(str(またはint), ...) で strまたはintに変換
  • list() で リストに変換

複数行

単一の文字列が複数行

# 入力
3
111
222
333
n = int(input())  # 行数を受け取る

# str型のリストに変換する場合
print([input() for _ in range(n)])

# 出力 `['111', '222', '333']`


# int型のリストに変換する場合
print([int(input()) for _ in range(n)])

# 出力 `[111, 222, 333]`
  • for _ in range(n) を使って ninput() を繰り返す

出力

単純な単一文字列

# str型
print('42')  # `42`

# int型
print(42)  # `42`

リストの要素をスペース区切りで出力(要素がint型)

arr = [1, 2, 3, 4, 5]

# 方法1
print(' '.join(map(str, arr)))

# 方法2
print(*arr)

# 出力 `1 2 3 4 5`

リストの要素をスペース区切りで出力(要素がstr型)

arr = ['A','B','C','D','E']

# 方法1
print(' '.join(arr)) # mapでの型変換が不要

# 方法2
print(*arr)

# 出力 `A B C D E`
  • * を使うとリストの アンパック ができ、print() のデフォルトのスペース区切りで出力される

リストの要素をスペースなしで出力(要素がint型)

arr = [1, 2, 3, 4, 5]
# 方法1
print(''.join(map(str, arr)))

# 方法2
print(*arr, sep='')

# 出力 `12345`

リストの要素をスペースなしで出力(要素がstr型)

arr = ['A','B','C','D','E']

# 方法1
print(''.join(arr)) # mapでの型変換が不要

# 方法2
print(*arr, sep='')

# 出力 `ABCDE`

リストの要素を改行区切りで出力(要素がint型)

arr = [1, 2, 3, 4, 5]

# 方法1
print("\n".join(map(str, arr)))

# 方法2
print(*arr, sep='\n')

# 出力
#   1
#   2
#   3
#   4
#   5

リストの要素を改行区切りで出力(要素がstr型)

arr = ['A','B','C','D','E']

# 方法1
print("\n".join(arr)) # 型変換が不要

# 方法2
print(*arr, sep='\n')

# 出力
#   A
#   B
#   C
#   D
#   E

高速な入出力

入力

大量の入力を扱う場合、sys.stdin.read() を使うと 一括で入力を受け取る ことができる。

import sys

data = sys.stdin.read().split()  # 全ての入力を一括で受け取り、スペース・改行で分割
  • sys.stdin.read() は 標準入力をすべて読み込む
  • .split() で スペース・改行区切りでリストにする

出力

大量の出力がある場合、print() より sys.stdout.write() の方が高速。

import sys
sys.stdout.write("Hello\n")  # → Hello(改行あり)
  • sys.stdout.write()print() より 遅延が少なく高速
  • \n を明示しないと改行されないので注意
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?