python机试1:读取和输出数据

发布于:2025-03-09 ⋅ 阅读:(14) ⋅ 点赞:(0)

读取和输出数据在 LeetCode 和机试中也是很重要的基础。你需要掌握 文件读取、输入处理、输出优化,才能应对不同类型的题目和考试环境。以下是详细的知识点:


1. 标准输入与输出

Python 标准输入 input()

机试中,很多题目要求从标准输入 stdin 读取数据,通常使用:

n = int(input())  # 读取一个整数
s = input().strip()  # 读取一行字符串
arr = list(map(int, input().split()))  # 读取一行多个整数

常见场景:

  1. 读取单个整数
    n = int(input())  # 读取一个整数
    
  2. 读取一行多个整数
    arr = list(map(int, input().split()))
    
  3. 读取多行输入
    n = int(input())  
    for _ in range(n):
        x = int(input())  # 逐行读取
    
  4. 读取二维列表(矩阵)
    n, m = map(int, input().split())  # 读取行数和列数
    matrix = [list(map(int, input().split())) for _ in range(n)]
    

Python 标准输出 print()

基本用法:

print("Hello World")  # 输出字符串
print(42)  # 输出整数
print(3.14159)  # 输出浮点数

多变量输出(默认空格分隔)

a, b = 3, 5
print(a, b)  # 输出: 3 5

格式化输出

x = 3.14159
print(f"{x:.2f}")  # 输出: 3.14  (保留2位小数)

换行控制

print("Hello", end=" ")  # 取消换行
print("World")  # 输出: Hello World

2. 高效读取 & 写入(sys.stdin & sys.stdout)

在机试中,input() 在大数据情况下 读取速度慢,可以使用 sys.stdin.read() 进行 批量读取

import sys
data = sys.stdin.read().split()  # 读取所有输入并按空格分割

示例:

import sys
n = int(sys.stdin.readline().strip())  # 读取一行,去除换行符
arr = list(map(int, sys.stdin.readline().split()))  # 读取一行并转为整数列表

批量输出(减少 print() 调用,加速运行)

import sys
sys.stdout.write("Hello World\n")  # 速度比 print() 快

3. 读取文件 & 写入文件

有些机试允许文件输入输出:

# 读取文件
with open("input.txt", "r") as f:
    lines = f.readlines()

# 写入文件
with open("output.txt", "w") as f:
    f.write("Hello World\n")

4. 处理 JSON/CSV 数据

在数据分析、爬虫、或 AI 任务中,需要处理 JSON/CSV 格式数据:

JSON 处理

import json
# 读取 JSON
with open("data.json", "r") as f:
    data = json.load(f)  
print(data["name"])  # 访问字段

# 写入 JSON
with open("output.json", "w") as f:
    json.dump(data, f, indent=4)

CSV 处理

import csv
# 读取 CSV
with open("data.csv", "r") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

# 写入 CSV
with open("output.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["Name", "Age"])
    writer.writerow(["Alice", 25])

5. 处理特殊格式输入

✅ 示例:读取以逗号分隔的输入

arr = list(map(int, input().split(",")))  # 读取 "1,2,3,4" -> [1, 2, 3, 4]

✅ 示例:读取 key=value 格式输入

data = {}
for _ in range(int(input())):
    key, value = input().split("=")
    data[key] = value
print(data)

6. 如何提高输入输出效率?

减少 input() 调用

# Bad
n = int(input())
arr = []
for _ in range(n):
    arr.append(int(input()))

# Good
import sys
n = int(sys.stdin.readline())
arr = list(map(int, sys.stdin.read().split()))

减少 print() 调用

# Bad
for num in arr:
    print(num)

# Good
import sys
sys.stdout.write("\n".join(map(str, arr)) + "\n")

使用 sys.stdin.read() 处理大数据

import sys
data = sys.stdin.read().split()  # 读取所有数据并按空格拆分

总结

在 LeetCode 和机试中,掌握输入输出是必备技能:

  1. input()print() 基础
  2. sys.stdin.readline() 提高读取速度
  3. sys.stdout.write() 批量输出
  4. 文件读写(open()jsoncsv
  5. 特殊格式输入处理
  6. 减少 print() 调用,加速大规模输出

如果你要刷 LeetCode 或参加机试,建议多练习 处理大数据输入输出的技巧,这样可以让代码更高效!💪