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 小时前
#C语言——刷题攻略:牛客编程入门训练(十一):攻克 循环控制(三),轻松拿捏!
c语言·开发语言·经验分享·学习·visual studio
海天一色y1 小时前
Pycharm(二十一)递归删除文件夹
ide·python·pycharm
励志码农3 小时前
JavaWeb 30 天入门:第二十三天 —— 监听器(Listener)
java·开发语言·spring boot·学习·servlet
天高云淡ylz3 小时前
子网掩码的隐形陷阱:为何能ping通却无法HTTPS访问
开发语言·php
希望20175 小时前
Golang Panic & Throw & Map/Channel 并发笔记
开发语言·golang
朗迹 - 张伟5 小时前
Golang安装笔记
开发语言·笔记·golang
yzx9910135 小时前
生活在数字世界:一份人人都能看懂的网络安全生存指南
运维·开发语言·网络·人工智能·自动化
小周同学@5 小时前
谈谈对this的理解
开发语言·前端·javascript
乔巴先生246 小时前
LLMCompiler:基于LangGraph的并行化Agent架构高效实现
人工智能·python·langchain·人机交互
橙*^O^*安6 小时前
Go 语言基础:变量与常量
运维·开发语言·后端·golang·kubernetes