文章目录
-
- [1. Python 和 C++ 思维差异](#1. Python 和 C++ 思维差异)
- [2. 基础语法](#2. 基础语法)
- [3. 字符串 `str`](#3. 字符串
str) - [4. 列表 `list`](#4. 列表
list) - [5. 字典 `dict`](#5. 字典
dict) - [6. 集合 `set`](#6. 集合
set) - [7. 元组 `tuple`](#7. 元组
tuple) - [8. 切片 `slice`](#8. 切片
slice) - [9. 自动化脚本高频模板](#9. 自动化脚本高频模板)
- [10. 编码习惯](#10. 编码习惯)
-
- 命名建议
- [优先使用 f-string](#优先使用 f-string)
- [遍历字典优先用 `.items()`](#遍历字典优先用
.items()) - [需要默认值时优先用 `.get()`](#需要默认值时优先用
.get()) - 修改列表时谨慎边遍历边删除
- 排序选择
- [11. 常见错误速查](#11. 常见错误速查)
- [12. 一页记忆版](#12. 一页记忆版)
1. Python 和 C++ 思维差异
| 主题 | C++ 常见写法/习惯 | Python 常见写法/习惯 |
|---|---|---|
| 变量声明 | int x = 1; |
x = 1,动态类型 |
| 布尔值 | true / false |
True / False,首字母大写 |
| 空值 | nullptr / NULL |
None |
| 代码块 | {} |
缩进,通常 4 个空格 |
| 逻辑与或非 | `&& / | |
| 字符串拼接 | + 或流输出 |
数字要先 str(),更推荐 f-string |
| 数组 | vector<T> |
list,可混合类型,但工程中建议保持同质 |
| 哈希表 | unordered_map |
dict |
| 集合 | set |
set,无序去重 |
| 不可变数组 | tuple |
tuple,常用于多返回值和固定结构 |
| 遍历带索引 | for (int i=0;...) |
for i, x in enumerate(arr): |
2. 基础语法
变量和类型
python
age = 21
price = 9.99
name = "Vect"
is_student = True
print(type(age)) # <class 'int'>
print(type(price)) # <class 'float'>
print(type(name)) # <class 'str'>
print(type(is_student))# <class 'bool'>
实战经验:
- Python 不需要显式声明类型,但实际编码中变量名要表达清楚含义
- 字符串和数字不能直接相加:
python
age = 21
print("age = " + str(age))
print(f"age = {age}") # 更推荐
输入输出
python
name = "Vect"
age = 21
print(f"hello, {name}. You are {age} years old.")
num = int(input("请输入一个数字:"))
print(f"你输入的数字 + 1 是:{num + 1}")
注意:
input()返回的一定是字符串- 读取数字要手动转换:
int(input())、float(input()) print(a, b, c)默认用空格分隔print(x, end=" ")可以避免换行
批量读入整数:
python
nums = list(map(int, input().split()))
读取逗号分隔内容:
python
items = input().split(",")
条件判断
python
score = 85
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
else:
print("D")
更 Pythonic 的区间判断:
python
if 90 <= score <= 100:
print("优秀")
elif 80 <= score < 90:
print("良好")
循环
python
for i in range(1, 11):
print(i) # 1 到 10
for i in range(0, 8, 2):
print(i) # 0, 2, 4, 6
for i in range(7, -1, -1):
print(i) # 7 到 0
range(start, stop, step) 是左闭右开区间:[start, stop)
遍历列表:
python
arr = [10, 20, 30]
for x in arr:
print(x)
带索引遍历,工程中高频:
python
for i, x in enumerate(arr):
print(i, x)
while 与 break / continue:
python
num = 0
while num < 10:
num += 1
if num == 3:
continue
if num == 6:
break
print(num)
常见小坑
python
# 不建议覆盖内置函数名
sum = 0 # 不推荐,会覆盖内置 sum()
str = "abc" # 不推荐,会覆盖内置 str()
list = [] # 不推荐,会覆盖内置 list()
推荐写法:
python
total = 0
text = "abc"
items = []
3. 字符串 str
字符串是不可变对象,不能原地修改:
python
s = "hello world"
s = "H" + s[1:]
print(s) # Hello world
创建
python
s1 = "hello"
s2 = 'hello'
s3 = """multi
line
string"""
索引和切片
python
s = "Python"
print(s[0]) # P
print(s[-1]) # n
print(s[1:4]) # yth
print(s[::2]) # Pto
print(s[::-1]) # nohtyP
切片模板:
python
seq[start:end:step]
常用切片:
python
s[:3] # 前 3 个
s[-3:] # 后 3 个
s[::-1] # 反转
常用方法
python
s = " hello world "
s.strip() # 去除两端空白
s.upper() # 转大写
s.lower() # 转小写
s.replace("old", "new")
s.split() # 按空白切分
s.split(",") # 按逗号切分
"hello" in s # 判断子串是否存在
s.find("l") # 第一次出现位置,找不到返回 -1
s.count("l") # 出现次数
s.startswith("h") # 是否以 h 开头
s.endswith(".py") # 是否以 .py 结尾
"-".join(["a", "b", "c"]) # a-b-c
自动化脚本常用场景:
python
filename = "main.py"
if filename.endswith(".py"):
print("Python 文件")
line = " apple, banana, orange "
items = [x.strip() for x in line.split(",")]
print(items) # ['apple', 'banana', 'orange']
回文判断:
python
s = "level"
print(s == s[::-1])
4. 列表 list
类似 vector,但 Python list 可以放不同类型;一个列表里保持同一种数据类型,别装逼
创建
python
a = [1, 2, 3]
b = []
c = list()
d = list("abc") # ['a', 'b', 'c']
增加元素
python
a = [1, 2, 3]
a.append(4) # 尾插单个元素
a.insert(0, 100) # 指定位置插入
a.extend([5, 6, 7]) # 追加另一个可迭代对象的所有元素
注意:
python
a.append([5, 6]) # 把整个列表作为一个元素插入
a.extend([5, 6]) # 把 5 和 6 分别插入
删除元素
python
a = [10, 20, 30, 40]
x = a.pop() # 删除并返回最后一个元素
y = a.pop(1) # 删除并返回下标 1 的元素
a.remove(30) # 删除第一个值为 30 的元素,不存在会报错
del a[0] # 按下标删除
安全删除建议:
python
if 30 in a:
a.remove(30)
遍历
python
for x in a:
print(x)
for i, x in enumerate(a):
print(i, x)
常用函数和方法
python
a = [1, 21, 7, 14, 5, 3]
len(a) # 长度
max(a) # 最大值
min(a) # 最小值
sum(a) # 求和
a.count(7) # 值 7 出现次数
a.index(21) # 值 21 第一次出现的下标,不存在会报错
a.reverse() # 原地反转
a.sort() # 原地升序排序
排序相关:
python
a = [3, 1, 2]
b = sorted(a) # 返回新列表,a 不变
a.sort() # 原地排序,a 改变
a.sort(reverse=True) # 降序
sorted(a, reverse=True) # 返回降序新列表
列表推导式
适合脚本中的批量转换、过滤
python
squares = [x * x for x in range(1, 6)]
带条件过滤:
python
nums = [1, 2, 3, 4, 5, 6]
evens = [x for x in nums if x % 2 == 0]
字符串清洗:
python
words = [" apple ", " banana ", " orange "]
clean_words = [word.strip() for word in words]
筛选文件:
python
files = ["a.py", "b.txt", "c.py", "d.md"]
py_files = [file for file in files if file.endswith(".py")]
5. 字典 dict
对应 C++ unordered_map,是 Python 工程中最高频的数据结构之一
创建
python
d1 = {}
d2 = dict()
d3 = {"apple": 3, "banana": 5}
d4 = dict(apple=3, banana=5)
注意:{} 表示空字典;空集合要写 set()。
增删改查
python
score = {}
score["Alice"] = 85 # 增加
score["Alice"] = 90 # 修改
print(score["Alice"]) # 直接访问,不存在会报错
print(score.get("Bob")) # 不存在返回 None
print(score.get("Bob", 0)) # 不存在返回默认值 0
判断 key 是否存在:
python
if "Alice" in score:
print(score["Alice"])
删除:
python
del score["Alice"] # key 不存在会报错
value = score.pop("Bob", None) # 更安全,带默认值
遍历
python
scores = {
"Alice": 90,
"Bob": 85,
"Tom": 70,
}
for name in scores:
print(name)
for name in scores.keys():
print(name)
for score in scores.values():
print(score)
for name, score in scores.items():
print(name, score)
合并字典
python
d = {"a": 1, "b": 2}
d.update({"c": 3, "a": 101})
print(d) # {'a': 101, 'b': 2, 'c': 3}
Python 3.9+ 也可以:
python
d3 = d1 | d2
计数模板
python
words = ["apple", "banana", "apple", "orange", "banana", "apple"]
cnt = {}
for word in words:
cnt[word] = cnt.get(word, 0) + 1
print(cnt)
工程中更推荐:
python
from collections import Counter
cnt = Counter(words)
print(cnt["apple"])
分组模板
python
items = ["apple", "ant", "banana", "book"]
groups = {}
for item in items:
key = item[0]
groups.setdefault(key, []).append(item)
print(groups) # {'a': ['apple', 'ant'], 'b': ['banana', 'book']}
字典推导式
python
nums = [1, 2, 3]
square_map = {x: x * x for x in nums}
过滤字典:
python
scores = {"Alice": 90, "Bob": 85, "Tom": 70}
good = {name: score for name, score in scores.items() if score >= 80}
6. 集合 set
用于去重、判断是否存在、求交并差
创建
python
s1 = set()
s2 = {1, 2, 3}
s3 = set([1, 2, 2, 3]) # {1, 2, 3}
s4 = set("hello")
注意:
python
a = {} # 空 dict,不是 set
b = set() # 空 set
增删查
python
s = set()
s.add("app")
s.add("mysql")
s.remove("app") # 不存在会报错
s.discard("mysql") # 不存在也不会报错,更安全
if "cpp" in s:
print("exists")
遍历和排序输出
python
s = {"app", "bpp", "cpp"}
for x in s:
print(x) # 无序
for x in sorted(s):
print(x) # 有序输出
集合运算
python
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # 并集 {1, 2, 3, 4, 5}
print(a & b) # 交集 {3}
print(a - b) # 差集 {1, 2}
print(a ^ b) # 对称差集 {1, 2, 4, 5} (A ∪ B) - (A ∩ B)
自动化脚本常用场景:
python
files = ["a.txt", "b.py", "a.txt"]
if len(files) != len(set(files)):
print("has duplicate")
快速去重:
python
nums = [1, 2, 2, 3]
unique_nums = list(set(nums)) # 不保证原顺序
保持原顺序去重:
python
nums = [1, 2, 2, 3, 1]
unique_nums = list(dict.fromkeys(nums))
print(unique_nums) # [1, 2, 3]
7. 元组 tuple
不可修改的固定序列,适合表示固定结构和函数多返回值
创建
python
t1 = (1, 2, 3)
t2 = ()
t3 = tuple([1, 2, 3])
t4 = ("Alice", 20)
单元素元组必须加逗号:
python
a = (1) # int
b = (1,) # tuple
常用方法
python
t = (1, 3, 4, 5, 3)
print(t.count(3))
print(t.index(1))
解包
python
point = (3, 4)
x, y = point
person = ("Tom", 18, "Shanghai")
name, age, city = person
函数多返回值本质上常用元组:
python
def get_point():
return 3, 4
x, y = get_point()
交换变量:
python
a, b = b, a
8. 切片 slice
适用于字符串、列表、元组等序列
python
seq[start:end:step]
常用模板:
python
s = "helloworld"
s[:3] # 前 3 个
s[-3:] # 后 3 个
s[::-1] # 反转
s[::2] # 每隔一个取一个
列表切片:
python
a = [1, 2, 3, 4, 5, 6]
print(a[:3]) # [1, 2, 3]
print(a[-2:]) # [5, 6]
print(a[::2]) # [1, 3, 5]
切片会产生新对象:
python
b = a[:]
常用于浅拷贝,但如果元素本身是嵌套可变对象,仍要注意深浅拷贝问题
9. 自动化脚本高频模板
读取一行多个整数
python
nums = list(map(int, input().split()))
过滤指定后缀文件名
python
files = ["a.py", "b.txt", "c.py"]
py_files = [file for file in files if file.endswith(".py")]
清洗字符串列表
python
raw = [" apple ", " banana ", " orange "]
clean = [x.strip() for x in raw]
统计词频
python
words = ["apple", "banana", "apple"]
cnt = {}
for word in words:
cnt[word] = cnt.get(word, 0) + 1
查找高分用户
python
scores = {"Alice": 90, "Bob": 85, "Tom": 70}
for name, score in scores.items():
if score >= 80:
print(name)
判断重复
python
items = ["a", "b", "a"]
has_duplicate = len(items) != len(set(items))
安全访问字典
python
config = {"timeout": 10}
timeout = config.get("timeout", 5)
retry = config.get("retry", 3)
安全删除字典 key
python
d = {"a": 1}
value = d.pop("b", None)
按规则转换列表
python
nums = [1, 2, 3, 4]
squares = [x * x for x in nums]
evens = [x for x in nums if x % 2 == 0]
10. 编码习惯
命名建议
推荐:
python
user_name = "Vect"
total_score = 100
py_files = []
避免:
python
str = "abc"
list = [1, 2]
sum = 0
原因:这些名字会覆盖 Python 内置函数或类型
优先使用 f-string
python
name = "Vect"
age = 21
print(f"{name} is {age} years old")
比字符串拼接更清晰,也避免数字转字符串的问题。
遍历字典优先用 .items()
python
for key, value in d.items():
print(key, value)
比先遍历 key 再 d[key] 更直接。
需要默认值时优先用 .get()
python
count = cnt.get(word, 0)
避免访问不存在 key 导致 KeyError。
修改列表时谨慎边遍历边删除
不推荐:
python
for x in nums:
if x % 2 == 0:
nums.remove(x)
推荐生成新列表:
python
nums = [x for x in nums if x % 2 != 0]
排序选择
python
a.sort() # 原地改 a
b = sorted(a) # 返回新列表,不改 a
工程中如果后续还需要原列表,优先用 sorted()
11. 常见错误速查
| 错误 | 原因 | 解决 |
|---|---|---|
TypeError: can only concatenate str... |
字符串和数字直接 + |
用 str(x) 或 f-string |
KeyError |
访问不存在的字典 key | 用 get() 或先判断 in |
ValueError: list.remove(x): x not in list |
删除不存在元素 | 先判断 if x in arr |
IndexError |
下标越界 | 检查 len(arr) |
TypeError: 'str' object does not support item assignment |
字符串不可变 | 创建新字符串 |
SyntaxError |
引号嵌套错误、括号不匹配、缩进错误 | 检查语法和缩进 |
例如引号嵌套:
python
# 错误
# print(f"文件名后缀是否为.py:{s.endswith(".py")}")
# 正确
print(f"文件名后缀是否为.py:{s.endswith('.py')}")
12. 一页记忆版
python
# 输入
n = int(input())
nums = list(map(int, input().split()))
# 输出
print(f"n = {n}")
# 循环
for i in range(n):
print(i)
for i, x in enumerate(nums):
print(i, x)
# 字符串
s = " hello.py "
s = s.strip()
s.endswith(".py")
s.split(".")
"-".join(["a", "b", "c"])
s[::-1]
# list
arr = []
arr.append(1)
arr.extend([2, 3])
arr.pop()
arr.sort()
[x * x for x in arr]
[x for x in arr if x % 2 == 0]
# dict
cnt = {}
for x in arr:
cnt[x] = cnt.get(x, 0) + 1
for k, v in cnt.items():
print(k, v)
# set
unique = set(arr)
has_duplicate = len(arr) != len(set(arr))
# tuple / 解包
x, y = (3, 4)
a, b = b, a