核心知识点
input()
vs sys.stdin.readline()
input()
: 内置函数,使用方便,但速度较慢。它会读取一行,去除末尾的换行符 \n
,并返回一个字符串。
sys.stdin.readline()
: 速度更快,因为它使用了缓冲区。它会读取一行,但保留 末尾的换行符 \n
。因此,通常需要配合 .strip()
或 .rstrip()
使用。
print()
vs sys.stdout.write()
print()
: 内置函数,功能强大,可以自动在末尾添加换行符,但相对较慢。
sys.stdout.write()
: 速度更快,但只接受字符串作为参数,且不会 自动添加换行符,需要手动添加 '\n'
。
对于追求极致性能的竞赛,推荐使用 sys
模块。
场景1:读取单行数据 1.1 读取一个字符串 1 2 3 4 5 6 7 8 9 10 s = input () import syss = sys.stdin.readline().strip()
1.2 读取一个整数或浮点数 1 2 3 4 5 6 7 8 n = int (input ()) f = float (input ()) import sysn = int (sys.stdin.readline()) f = float (sys.stdin.readline())
场景2:读取单行内的多个值 这是最常见的场景之一,一行中有多个由空格隔开的数字或字符串。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 import sysa_str, b_str = input ().split() a, b = int (a_str), int (b_str) a, b = map (int , input ().split()) n, s = input ().split() n = int (n) a, b = map (int , sys.stdin.readline().split()) nums_str = input ().split() nums = [int (x) for x in nums_str] nums = list (map (int , input ().split())) nums = list (map (int , sys.stdin.readline().split()))
场景3:读取固定行数的多行数据 通常第一行会给出一个整数 N
,表示接下来有 N
行数据。
3.1 每行只有一个数据 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 import sysn = int (sys.stdin.readline()) data = [] for _ in range (n): line = sys.stdin.readline().strip() data.append(line)
3.2 每行有多个数据 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 import sysn = int (sys.stdin.readline()) matrix = [] for _ in range (n): row = list (map (int , sys.stdin.readline().split())) matrix.append(row)
场景4:读取不定行数的数据,直到文件末尾 (EOF) 这种场景下,输入没有明确的结束标志,需要一直读取直到输入流结束。
当 input()
或 sys.stdin.readline()
读到文件末尾时,会引发 EOFError
或返回一个空字符串。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 import syslines = [] while True : try : line = sys.stdin.readline().strip() if not line: break nums = list (map (int , line.split())) lines.append(nums) except EOFError: break
4.2 方法二:直接遍历 sys.stdin
(更 Pythonic,推荐) sys.stdin
本身就是一个可迭代对象,当输入结束时,循环会自动停止。
1 2 3 4 5 6 7 8 9 10 import sysfor line in sys.stdin: line = line.strip() if not line: continue a, b = map (int , line.split())
场景5:复杂的多组测试数据 题目通常会先给一个测试组数 T
,然后循环 T
次处理每一组数据。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 import systry : t = int (sys.stdin.readline()) except (ValueError, IndexError): t = 0 for _ in range (t): n = int (sys.stdin.readline()) nums = list (map (int , sys.stdin.readline().split())) result = sum (nums) print (result)
二、 输出 (Output) 场景1:输出单个值 1 2 3 4 5 6 7 8 9 result = 100 print (result) import sysresult = 100 sys.stdout.write(str (result) + '\n' )
场景2:在一行输出多个值,用空格隔开 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 data = [1 , 2 , 3 , 4 ] print (*data) print (' ' .join(map (str , data)))for i, item in enumerate (data): print (item, end=' ' ) print () import syssys.stdout.write(' ' .join(map (str , data)) + '\n' )
场景3:格式化输出 3.1 使用 f-string (Python 3.6+,推荐) f-string 是目前最现代、最易读的格式化方法。
1 2 3 4 5 6 7 name = "Alice" score = 95.5 print (f"Name: {name} , Score: {score} " )pi = 3.1415926 print (f"{pi:.2 f} " )
1 2 3 4 5 6 7 name = "Bob" score = 88.0 print ("Name: {}, Score: {}" .format (name, score))pi = 3.1415926 print ("{:.2f}" .format (pi))
三、完整 ACM 模式模板 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 import sysdef solve (): result = "your_answer" sys.stdout.write(str (result) + '\n' ) def main (): try : t = int (sys.stdin.readline()) except (ValueError, IndexError): t = 1 for _ in range (t): solve() if __name__ == "__main__" : main()
总结
操作
方便但慢 (小数据量)
高效推荐 (大数据量)
读一行
s = input()
s = sys.stdin.readline().strip()
读整数
n = int(input())
n = int(sys.stdin.readline())
读一行多个数
arr = list(map(int, input().split()))
arr = list(map(int, sys.stdin.readline().split()))
读到EOF
try-except
块
for line in sys.stdin:
输出
print(var)
sys.stdout.write(str(var) + '\n')
输出列表
print(*my_list)
sys.stdout.write(' '.join(map(str, my_list)) + '\n')
始终优先使用 sys.stdin.readline()
,并记得用 .strip()
或 .rstrip()
去掉换行符。