use_python
输入
readline() 、readlines() 和 read() 区别
import sys
# 输入:
# Hello
# World
# !
# 使用 readline()
line1 = sys.stdin.readline() # "Hello\n"
line2 = sys.stdin.readline() # "World\n"
line3 = sys.stdin.readline() # "!\n"
line4 = sys.stdin.readline() # ""
# 使用 readlines()
lines = sys.stdin.readlines() # ["Hello\n", "World\n", "!\n"]
# 使用 read()
content = sys.stdin.read() # "Hello\nWorld\n!\n"strip() 函数
s = " hello \n\t"
print(repr(s.rstrip())) # 移除右侧空白字符 → "' hello'"
print(repr(s.lstrip())) # 移除左侧空白字符 → "'hello \n\t'"
print(repr(s.strip())) # 移除两侧空白字符 → "'hello'"split() 函数
str.split(sep=None, maxsplit=-1)- sep:分隔符,默认为任何空白字符
- maxsplit:最大分割次数,默认为 -1(不限制)
空字典 vs 空集合
a = {} # 空字典(dict)
b = set() # 空集合(set)
print(type(a)) # <class 'dict'>
print(type(b)) # <class 'set'>如何创建空集合
# ❌ 错误:这是字典,不是集合
a = {}
# ✅ 正确:创建空集合
b = set()
# ✅ 正确:创建带初始值的集合
c = {1, 2, 3}记忆方法
| 写法 | 类型 | 说明 |
|---|---|---|
{} |
dict | 大括号里有键值对或为空时是字典 |
{1} |
set | 大括号里只有值时是集合 |
set() |
set | 明确表示集合 |
典型应用:差分数组
diff = {}
# 对区间 [l, r) 加 v
diff[l] = diff.get(l, 0) + v # 起点加 v
diff[r] = diff.get(r, 0) - v # 终点减 v常见应用场景
# 交换变量
a, b = b, a
# 函数返回多个值
def get_point():
return (3, 5)
x, y = get_point() # x=3, y=5use_python
https://mingsm17518.github.io/2026/03/18/algorithm/others/use_python/