LoginSignup
39
37

More than 1 year has passed since last update.

【Python】競プロ用様々な入力の受け取り方まとめ

Last updated at Posted at 2023-02-02

はじめに

調べて分かったものもあれば自分で考え出したものもあります。
より短い書き方などあったら教えていただけると幸いです。
新しい入力形式があったら随時追加予定です

数値(整数)

1文字の整数

入力例

2

受け取り方

N = int(input())

2文字以上の整数(別変数として受け取る)

入力例

2 3

受け取り方

N, M = map(int, input().split())

受け取りたい値の個数に左辺の文字数を合わせる

配列

入力例

2 3 5

受け取り方

A = [int(x) for x in input().split()]
# or
A = list(map(int, input().split()))
# or
A = [*map(int, input().split())]

N行→1つの配列

入力例

0
1
2
3
4

受け取り方

a = [int(input()) for _ in range(N)]
# print(a) -> [0, 1, 2, 3, 4]

N行2次元配列→1つの変数

入力例

1 2 3 4
5 6 7 8
9 10 11 12

受け取り方

a = [ list(map(int,input().split(" "))) for _ in range(N)]
# print(a)
# [[1, 2, 3, 4], 
#  [5, 6, 7, 8], 
#  [9, 10, 11, 12]]

N行M列2次元配列→縦1列を1つの配列として別変数で

N = 4, M = 3の場合

入力例

1 2 3
4 5 6
7 8 9
10 11 12

受け取り方

left = []
mid = []
right = []
a = [ list(map(int,input().split(" "))) for _ in range(N)]
for i in range(N):
    left.append(a[i][0])
    mid.append(a[i][1])
    right.append(a[i][2])
# print(left)
# -> [1, 4, 7, 10]
# print(mid)
# -> [2, 5, 8, 11]
# print(right)
# -> [3, 6, 9, 12]

これもっといい方法ありそう

【追記】タプルでの受け取り方

@Cartelet さん、コメントありがとうございます!

a = [map(int,input().split(" ")) for _ in range(N)]
left, mid, right = map(list, zip(*a))
# print(left)
# -> (1, 4, 7, 10)

まとめてリストに変換する方法はあるのでしょうか...?
left = list(left)で1つずつ変換していく方法しか思いつきません。

追記

a = [map(int,input().split(" ")) for _ in range(N)]
left, mid, right = map(list, zip(*a))

これでタプルではなくリストで受け取れるようです。

文字列

1つの文字

入力例

a

受け取り方

S = input()

文字列をそのまま

入力例

hello

受け取り方

S = input()
# print(S) -> 'hello'

文字列を1文字ずつの配列として

入力例

hello

受け取り方

S = list(input())
# print(S) -> ['h', 'e', 'l', 'l', 'o']

N個の文字列

入力例

good morning
hello
good bye

受け取り方

S = [input() for _ in range(N)]
# print(S) -> ['good morning', 'hello', 'good bye']

N個の文字列(各文字列を1文字ずつばらして)

入力例

good morning
hello
good bye

受け取り方

S = [list(input()) for _ in range(N)]
# or
S = [[*input()] for _ in range(N)]
# print(S)
# [['g', 'o', 'o', 'd', ' ', 'm', 'o', 'r', 'n', 'i', 'n', 'g'], 
#  ['h', 'e', 'l', 'l', 'o'], 
#  ['g', 'o', 'o', 'd', ' ', 'b', 'y', 'e']]
自分で考えた方法.py
S = []
for i in range(N):
    S.append(list(input()))

コメントに感謝

@shiracamus さん、@Carteletさん
ありがとうございます!
もっと他の記事読んだり自分で考えたりして簡単な書き方探してみます。

39
37
7

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
39
37