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

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


1. 标准输入与输出

Python 标准输入 input()

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

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

常见场景:

  1. 读取单个整数

    python 复制代码
    n = int(input())  # 读取一个整数
  2. 读取一行多个整数

    python 复制代码
    arr = list(map(int, input().split()))
  3. 读取多行输入

    python 复制代码
    n = int(input())  
    for _ in range(n):
        x = int(input())  # 逐行读取
  4. 读取二维列表(矩阵)

    python 复制代码
    n, m = map(int, input().split())  # 读取行数和列数
    matrix = [list(map(int, input().split())) for _ in range(n)]

Python 标准输出 print()

基本用法:

python 复制代码
print("Hello World")  # 输出字符串
print(42)  # 输出整数
print(3.14159)  # 输出浮点数

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

python 复制代码
a, b = 3, 5
print(a, b)  # 输出: 3 5

格式化输出

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

换行控制

python 复制代码
print("Hello", end=" ")  # 取消换行
print("World")  # 输出: Hello World

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

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

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

示例:

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

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

python 复制代码
import sys
sys.stdout.write("Hello World\n")  # 速度比 print() 快

3. 读取文件 & 写入文件

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

python 复制代码
# 读取文件
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 处理

python 复制代码
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 处理

python 复制代码
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. 处理特殊格式输入

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

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

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

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

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

减少 input() 调用

python 复制代码
# 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() 调用

python 复制代码
# Bad
for num in arr:
    print(num)

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

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

python 复制代码
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 或参加机试,建议多练习 处理大数据输入输出的技巧,这样可以让代码更高效!💪

相关推荐
胖达不服输1 小时前
「日拱一码」020 机器学习——数据处理
人工智能·python·机器学习·数据处理
吴佳浩2 小时前
Python入门指南-番外-LLM-Fingerprint(大语言模型指纹):从技术视角看AI开源生态的边界与挑战
python·llm·mcp
吴佳浩2 小时前
Python入门指南-AI模型相似性检测方法:技术原理与实现
人工智能·python·llm
liulilittle2 小时前
LinkedList 链表数据结构实现 (OPENPPP2)
开发语言·数据结构·c++·链表
叶 落2 小时前
计算阶梯电费
python·python 基础·python 入门
2401_891957313 小时前
list的一些特性(C++)
开发语言·c++
二十雨辰3 小时前
[尚庭公寓]07-Knife快速入门
java·开发语言·spring
Python大数据分析@3 小时前
Origin、MATLAB、Python 用于科研作图,哪个最好?
开发语言·python·matlab
编程零零七3 小时前
Python巩固训练——第一天练习题
开发语言·python·python基础·python学习·python练习题
我爱Jack4 小时前
时间与空间复杂度详解:算法效率的度量衡
java·开发语言·算法