2
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?

More than 3 years have passed since last update.

Python標準入力

2
Last updated at Posted at 2021-06-29

競プロやコーディングテストで使用していた自分用のメモになります。
よくあるパターンを3つ簡素にまとめています。

パターン1

(入力例)
123 789
------------------------------------------
# 解法1
nums = list(map(int, input().split())) 
print(nums[0]) # Int:123
print(nums[1]) # Int:738

# 解法2(個数が既知のとき)
x,y = list(map(int, input().split()))
print(x) # Int:123
print(y) # Int:738

パターン2

(入力例)
1
2
3
4
------------------------
import sys
nums = []
for l in sys.stdin:
    nums.append(int(l))
print(nums) # Int:[1,2,3,4]

パターン3

(入力例)
1 2
3 4
5 6
7 8
9 0
--------------------------------------
# 解法1(行数が未知)
import sys
nums = []
for l in sys.stdin:
  l_tmp = l.replace("\n","").split()
  l_tmp = list(map(int,l_tmp))
  nums.append(l_tmp)
print(nums) # Int:[[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]

# 解法2(行数が既知)
xy = [map(int, input().split()) for _ in range(5)]
x, y = [list(i) for i in zip(*xy)]
print(x) # Int:[1, 3, 5, 7, 9]
print(y) # Int:[2, 4, 6, 8, 0]
(入力例)
a
!a
b
!c
d
!d
--------------------------------------
# 解法1(行数が未知)
import sys
nums = []
for l in sys.stdin:
  l_tmp = l.replace("\n","").split()
  nums.append(l_tmp)
print(nums) # str:[['a'], ['!a'], ['b'], ['!c'], ['d'], ['!d']]

よく使う実装のメモ

★各桁の値の取得

num = 242092
num_s = str(num)
for i in range(len(num_s)):
  print(num_s[i]) # str:2,4,2,0,9,2

★ソート系

list = [1,9,4,2,3,7]
list_upper = sorted(list) #[1, 2, 3, 4, 7, 9]
list_down = sorted(list,reverse=True) #[9, 7, 4, 3, 2, 1]

★Dequeで高速化を図る.

https://note.nkmk.me/python-collections-deque/
要素の追加・取り出し(削除)・アクセス(取得)が両端のみ → deque
両端以外の要素に頻繁にアクセス → リスト

from collections import deque
myList = [1,2,3]
myDeque = deque(myList)
last = myDeque.pop()
first = myDeque.popleft()
print(first,last) # Int:1,3
2
0
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
2
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?