Skip to content

🧱 数据类型与结构 ​

把基础语法比作字母和单词,数据类型就是 Python 世界的各种"积木块"。掌握它们,你就能拼出任何东西。

数字(Number) ​

Python 处理数字非常灵活:

python
# 整数 — 没有大小限制
a = 42
b = -7
huge = 10 ** 100  # 一亿亿亿...完全没问题

# 浮点数 — 带小数点的
pi = 3.14159
e = 2.71828

# 复数 — 科学计算常用
c = 3 + 4j
print(c.real, c.imag)  # 3.0 4.0

常用内置函数:

python
print(abs(-10))       # 10(绝对值)
print(round(3.14159, 2))  # 3.14(四舍五入)
print(max(1, 5, 3))   # 5(最大值)
print(min(1, 5, 3))   # 1(最小值)
print(pow(2, 10))     # 1024(2的10次方)

字符串(String) ​

创建与基本操作 ​

python
s1 = '你好'
s2 = "世界"
s3 = """多行
字符串"""       # 三个引号保留换行

# 拼接
print(s1 + s2)       # 你好世界
print(s1 * 3)        # 你好你好你好

# 索引(从 0 开始)
text = "Python"
print(text[0])       # P(第一个)
print(text[-1])      # n(最后一个)
print(text[-2])      # o(倒数第二个)

# 切片 [start:end:step] — 左闭右开
print(text[0:3])     # Pyt(索引 0、1、2)
print(text[:3])      # Pyt(省略开头 = 从0开始)
print(text[2:])      # thon(省略结尾 = 到末尾)
print(text[::2])     # Pto(每隔一个取)
print(text[::-1])    # nohtyP(反转字符串!)

f-string — 最好用的格式化方式 ​

python
name = "小雅"
age = 25
print(f"我叫{name},明年{age + 1}岁")

# 格式化数字
price = 12.5
print(f"价格:¥{price:.2f}")  # ¥12.50
print(f"{100:>5}")             # '  100'(右对齐,占5位)
print(f"{100:<5}")             # '100  '(左对齐)

常用字符串方法 ​

python
text = "  Hello, Python World!  "

print(text.strip())           # "Hello, Python World!"(去空格)
print(text.lower())           # "  hello, python world!  "
print(text.upper())           # "  HELLO, PYTHON WORLD!  "
print(text.replace("Python", "World"))  # 替换
print(text.split(","))        # ['  Hello', ' Python World!  '](分割)
print(",".join(["a", "b"]))   # "a,b"(用分隔符拼接)

# 判断
print("123".isdigit())        # True
print("abc".isalpha())        # True
print(text.startswith("  H")) # True
print("World" in text)        # True(成员判断)

列表(List)— 可变的有序集合 ​

这是 Python 中最常用的数据结构:

python
fruits = ["苹果", "香蕉", "橘子"]

# ---- 增 ----
fruits.append("葡萄")         # 末尾追加
fruits.insert(1, "草莓")      # 指定位置插入

# ---- 删 ----
fruits.pop()                  # 弹出最后一个
fruits.pop(0)                 # 弹出指定位置
fruits.remove("香蕉")         # 按值删除
del fruits[1]                 # 按索引删除

# ---- 改 ----
fruits[0] = "大苹果"          # 直接赋值

# ---- 查 ----
print(fruits[0])              # 索引访问
print(fruits[-1])             # 倒数第一个
print(len(fruits))            # 长度

# ---- 切片(和字符串一样) ----
nums = [0, 1, 2, 3, 4, 5]
print(nums[1:4])              # [1, 2, 3]
print(nums[::-1])             # [5, 4, 3, 2, 1, 0]

排序 ​

python
nums = [3, 1, 4, 1, 5, 9, 2]
nums.sort()                   # 原地排序 → [1, 1, 2, 3, 4, 5, 9]
nums.sort(reverse=True)       # 降序 → [9, 5, 4, 3, 2, 1, 1]

# sorted() 返回新列表,原列表不变
original = [3, 1, 2]
new_list = sorted(original)   # new_list = [1, 2, 3]

列表推导式 — Python 的优雅利器 ​

python
# 生成 1-10 的平方
squares = [x**2 for x in range(1, 11)]
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

# 带条件:只取偶数
evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

# 转大写
words = ["hello", "world"]
upper_words = [w.upper() for w in words]
# ['HELLO', 'WORLD']

元组(Tuple)— 不可变序列 ​

创建后不能修改:

python
point = (3, 4)
colors = ("红", "绿", "蓝")
single = (1,)    # 单元素元组必须有逗号!

print(point[0])  # 3(可以访问,但不能改)
# point[0] = 5   ❌ 报错!元组不可修改

# 元组解包
x, y = point     # x=3, y=4
a, b = b, a      # 一行交换两个变量的值!

什么时候用元组?

需要"这组数据创建后不能变"的场景——比如坐标、RGB 颜色值、函数返回多个值等。元组比列表稍快,也更安全。

字典(Dict)— 键值对映射 ​

Python 的"查字典"——用键(key)找值(value):

python
person = {
    "name": "小雅",
    "age": 25,
    "city": "杭州"
}

# ---- 增/改 ----
person["hobby"] = "摄影"       # 新增键
person["age"] = 26              # 修改已有键的值

# ---- 删 ----
del person["city"]

# ---- 查 ----
print(person["name"])           # 小雅
print(person.get("phone", "无")) # 无(安全访问,不存在返默认值)

直接访问不存在的键会报错

person["phone"] 如果 key 不存在会抛 KeyError。person.get("phone") 不存在返回 None,推荐用 get。

python
# ---- 遍历 ----
for key, value in person.items():
    print(f"{key}: {value}")

for key in person.keys():       # 只遍历键
    print(key)

for value in person.values():   # 只遍历值
    print(value)

# 检查键是否存在
if "name" in person:
    print("有 name 字段")

集合(Set)— 不重复的无序集合 ​

python
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

# 去重
nums = [1, 1, 2, 2, 3]
unique = set(nums)           # {1, 2, 3}

# 集合运算
print(a | b)   # {1, 2, 3, 4, 5, 6}  并集
print(a & b)   # {3, 4}              交集
print(a - b)   # {1, 2}              差集(在a不在b)
print(a ^ b)   # {1, 2, 5, 6}        对称差集(在一边不在两边)

# 常用方法
a.add(5)        # 添加
a.remove(1)     # 删除(元素不存在会报错)
a.discard(99)   # 安全删除(不存在不报错)

类型转换 ​

Python 内置类型之间可以灵活互转:

python
# 转整数
int("42")        # 42
int(3.14)        # 3(截断小数)

# 转字符串
str(42)          # "42"
str(True)        # "True"

# 转列表(可迭代的对象都能转)
list("hello")    # ['h', 'e', 'l', 'l', 'o']
list({1, 2, 3})  # [1, 2, 3]

# 转集合
set([1, 2, 2, 3])  # {1, 2, 3}

# 转元组
tuple([1, 2, 3])   # (1, 2, 3)

# 转布尔 — 空的东西为 False,非空为 True
bool("")          # False
bool("hello")     # True
bool(0)           # False
bool([])          # False

练习题 ​

  1. 给你一句话,用 Python 统计每个单词出现的次数(提示:split() + 字典)
  2. 列表 [5, 2, 9, 1, 5, 6],去重并排序
  3. 用列表推导式生成 1 到 100 的所有质数(只能被 1 和自身整除)
  4. 用户输入一串英文,反转每个单词的字母(例如 "hello world" → "olleh dlrow")
  5. 写一个通讯录程序,用字典存储姓名→电话,支持增删查

🎉 数据类型掌握了,你已经能写大部分日常脚本了!下节学函数与模块,让代码更有组织。

有问题或补充?欢迎留言