输入输出与常见读取模式速查
这页偏速查,不追求体系化,只保留我在写脚本、做题、处理临时数据时最常回看的输入模式。
读一个值
n = int(input())
name = input()
ratio = float(input())
一行多个值
x, y, z = map(int, input().split())
如果类型不同,可以先拆分再单独转换:
name, age, score = input().split()
age = int(age)
score = float(score)
读一行整数列表
numbers = list(map(int, input().split()))
第一位是数量,后面是数据
n, *nums = map(int, input().split())
这个写法很适合“第一位给长度,其余 是序列”的输入。
多行输入
固定行数
rows = []
for _ in range(3):
rows.append(list(map(int, input().split())))
读二维数组
matrix = []
for _ in range(n):
matrix.append(list(map(int, input().split())))
处理 EOF
如果不知道有多少行,直到文件结束为止,可以这样写:
while True:
try:
line = input().strip()
except EOFError:
break
if not line:
continue
print(line)
从文件读
with open("input.txt", "r", encoding="utf-8") as f:
for line in f:
values = line.strip().split()
print(values)
输出时常见的几种写法
print(x)
print(x, y, z)
print(*numbers)
print(" ".join(map(str, numbers)))
我自己的选择顺序
- 单个值:
int(input()) - 一行多个同类型值:
map(..., input().split()) - 想要列表:
list(map(...)) - 不定行输入:
try ... except EOFError - 文件输入:
with open(...)