Python处理算法题输入输出
Python处理算法题输入输出
内容
以下是 Python 处理算法题输入输出的详细指南,对比 C++ 习惯并给出高效写法:
一、输入处理核心方法
Python 处理输入通常比 C++ 更简洁,但要注意 数据类型转换 和 批量读取 优化。
1. 基础输入方法
| 场景描述 | C++ 写法 | Python 等效写法 | 
|---|---|---|
| 读取单行字符串 | cin >> s; | s = input().strip() | 
| 读取单个整数 | cin >> n; | n = int(input()) | 
| 读取一行多个整数 | cin >> a >> b >> c; | a, b, c = map(int, input().split()) | 
| 读取不确定数量的整行数字 | while(cin >> x) | nums = list(map(int, input().split())) | 
2. 高效读取方法(大数据量)
使用 sys.stdin 提升读取速度(类似 C++ 的 scanf):
import sys
# 读取单行并去除首尾空白符
line = sys.stdin.readline().strip()
# 一次性读取所有内容(适合密集输入)
data = sys.stdin.read().split()
3. 常见输入模式处理
场景1:多测试用例,每行一个整数
import sys
for line in sys.stdin:
    n = int(line.strip())
    # 处理逻辑
场景2:首行为n,后续n行数据
n = int(input())
for _ in range(n):
    s = input().strip()
场景3:矩阵输入(例如3x3网格)
matrix = [list(map(int, input().split())) for _ in range(3)]
场景4:不定长输入直到EOF
import sys
for line in sys.stdin:
    if not line.strip(): 
        break
    a, b = map(int, line.split())
二、输出处理技巧
Python 的输出灵活度极高,重点掌握 格式化字符串 和 批量输出。
1. 基础输出方法
| 需求 | C++ 写法 | Python 等效写法 | 
|---|---|---|
| 输出字符串+换行 | cout << s << endl; | print(s) | 
| 输出不换行 | cout << s; | print(s, end='') | 
| 输出多个变量用空格分隔 | cout << a << " " << b; | print(a, b)或print(f"{a} {b}") | 
2. 高级格式化输出
格式化字符串(类似 printf)
# 保留两位小数
print("{:.2f}".format(3.1415926))  # 输出 3.14
# 补前导零(如日期格式)
print("{:02d}-{:02d}".format(3, 5))  # 输出 03-05
# 使用 f-string(Python 3.6+)
name = "Alice"
print(f"Hello, {name}! Score: {95.5:.1f}")
输出列表/矩阵(元素用空格分隔)
arr = [1, 2, 3, 4]
print(" ".join(map(str, arr)))  # 输出 1 2 3 4
matrix = [[1,2], [3,4]]
for row in matrix:
    print(" ".join(map(str, row)))
三、实战代码模板
例1:A+B Problem
# 输入:多行,每行两个整数
import sys
for line in sys.stdin:
    a, b = map(int, line.strip().split())
    print(a + b)
例2:动态二维矩阵处理
# 输入:第一行两个整数n,m,接下来n行每行m个数字
n, m = map(int, input().split())
grid = [list(map(int, input().split())) for _ in range(n)]
# 输出:转置后的矩阵
for col in zip(*grid):
    print(" ".join(map(str, col)))
例3:不定长数组排序输出
# 输入:一行多个整数
nums = list(map(int, input().split()))
nums.sort()
print(" ".join(map(str, nums)))
四、性能优化建议
- 大规模数据:优先使用 sys.stdin.readline()或sys.stdin.read()一次性读取。
- 避免重复拼接字符串:批量处理数据后用 join输出。
- 减少IO次数:使用列表暂存结果,最后统一输出。
总结
\[\boxed{
\begin{aligned}
&\text{输入:} \\
&\quad \text{小数据→ } \texttt{input().strip()} \\
&\quad \text{大数据→ } \texttt{sys.stdin} \\
&\text{输出:} \\
&\quad \text{简单格式→ } \texttt{print(a, b)} \\
&\quad \text{复杂格式→ } \texttt{f-string} \\
&\text{模板:} \\
&\quad \text{循环读取+即时处理}
\end{aligned}
}
\]

 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号