快速掌握Python之基础语法和数据结构

文章目录

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)

whilebreak / 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
相关推荐
HHHHH1010HHHHH2 小时前
HTML函数在笔记本上卡顿怎么办_笔记本运行HTML函数优化操作【操作】
jvm·数据库·python
胡利光2 小时前
Harness Engineering 03|Eval & Trace Harness:验证和追溯的工程组织
android·开发语言·kotlin
djjdjdjdjjdj2 小时前
CSS如何实现元素淡入淡出显示_结合animation与opacity属性
jvm·数据库·python
m0_684501982 小时前
Go 中实现方法级执行时间监控的生产就绪方案
jvm·数据库·python
lsx2024062 小时前
SQL CREATE DATABASE
开发语言
直奔標竿2 小时前
Java开发者AI转型第九课!突破知识边界!企业级 RAG (检索增强生成) 核心架构与 ETL 管道初探
java·开发语言·人工智能·后端·spring
LiAo_1996_Y2 小时前
Python机器学习怎么防止数据泄漏_确保Scaler在Pipeline内拟合
jvm·数据库·python
夏恪2 小时前
php怎么实现数据库备份加密_php如何压缩并AES加密导出SQL文件
jvm·数据库·python
hhb_6182 小时前
R语言数据分析与可视化实战指南
开发语言·数据分析·r语言