LoginSignup
1
5

More than 3 years have passed since last update.

Python3の標準入力について

Last updated at Posted at 2019-07-22

AtCoderやpaizaで使用する(Python3の)標準入力についてメモ

1行1単語の取得

<入力データ>
12345

<記述コード>
str = input()
print(str)

<出力データ>
12345 (データ型:str)

int型データとして取得したい場合はint(input())と書く。
input()だとstr型として取得してしまう。

<入力データ>
12345

<記述コード>
str = int(input())
print(str)

<出力データ>
12345 (データ型:int)

1行複数単語(スペース区切り)を取得

<入力データ>
apple orange

<記述コード>
a, b= input().split()
print(a)
print(b)

<出力データ>
apple
orange (データ型:str)

int型データとして取得する場合はmap(int, input().split())と書く。

<入力データ>
123 456

<記述コード>
a, b= map(int, input().split())
print(a)
print(b)

<出力データ>
123
456 (データ型:int)

1行複数単語(スペース区切り)を取得 (リストとして)

<入力データ>
apple 123

<記述コード>
lists = list(input().split())
print(lists)

<出力データ>
['apple', '123'] (各要素のデータ型:str)

各要素をint型データとして取得する場合はlist(map(int, input().split()))と書く。

<入力データ>
123 555

<記述コード>
lists = list(map(int, input().split()))
print(lists)

<出力データ>
[123, 555] (各要素のデータ型:int)

1行目に単語数 n、2〜(n+1)行目1単語を取得

<入力データ>
3
apple
123
orange

<記述コード>
num = int(input())
lists = [input() for i in range(num)]
print(lists)

<出力データ>
['apple', '123', 'orange'] (各要素のデータ型:str)

リストの各要素をint型データとして取得する場合はinput()int(input())と書く。

<入力データ>
3
123
555
777

<記述コード>
num = int(input())
lists = [int(input()) for i in range(num)]
print(lists)

<出力データ>
[123, 555, 777] (各要素のデータ型:int)
1
5
1

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
1
5