LoginSignup
0
0

Pythonで標準入力を受け取る方法

Last updated at Posted at 2023-11-18

はじめに

本記事は、競プロやpaizaスキルチェックなどで必要な標準入力からのデータ取得について、Pythonでデータを受け取るための備忘録です。

標準入力について

標準入力(Standard Input)はユーザからデータを受け取るための方法。
プログラムへのキーボードなどからの入力を受けつける。
input()関数は、ユーザーから文字入力を受け取り、文字列として返す。

基本的なデータ取得

str = input()

# 前後の空白を取り除く
str = input().strip()

# 数としてintやfloatで取得する
int = int(input())

1行に複数個の入力データの場合

文字列データ

Input
りんご みかん ぶどう
strs = input().split()
print(strs)
#Output: ['りんご', 'みかん', 'ぶどう']

数値データ

Input
2 1 -5
nums = list(map(int, input().split()))
print(nums)
#Output: [2, 1, -5]

複数行に1つずつの入力データの場合

1行目で入力行数を受け取る。

文字列データ

Input
3
りんご
みかん
ぶどう
n = int(input())
strs = [(input()) for _ in range(n)]
print(strs)
#Output: ['りんご', 'みかん', 'ぶどう']

数値データ

Input
3
2
1
-5
n = int(input())
nums = [int(input()) for _ in range(n)]
print(nums)
#Output: [2, 1, -5]

複数行に複数個の入力データの場合

Input
3
1 4
2 -1 4
-5 3
n = int(input())
lists = [list(map(int, input().split())) for _ in range(n)]
print(lists)
#Output: [[1, 4], [2, -1, 4], [-5, 3]]
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