Python 基本数据类型

Python3 中有六个标准的数据类型,分别为:Number(数字)String(字符串)List(列表)Tuple(元组)Set(集合)Dictionary(字典)

其中:

  • 不可变数据(4个):Number(数字)、String(字符串)、bool(布尔)、Tuple(元组)
  • 可变数据(3个):List(列表)、Dictionary(字典)、Set(集合)

注意: bool 是 int 的子类,True 和 False 实际上就是 1 和 0。

一、Number(数字)

Python3 支持四种数字类型:

1.1 类型分类

类型说明示例
int整型,无大小限制a = 1
float浮点型(小数)b = 1.23
bool布尔型(int 的子类)c = True
complex复数d = 3 + 5j

1.2 基本运算

a, b, c, d = 20, 5.5, 1 + 3j, True

print(type(a))  # <class 'int'>
print(type(b))  # <class 'float'>
print(type(c))  # <class 'complex'>
print(type(d))  # <class 'bool'>
# 算术运算
print(10 + 3)    # 加法  → 13
print(10 - 3)    # 减法  → 7
print(10 * 3)    # 乘法  → 30
print(10 / 3)    # 除法  → 3.3333...
print(10 // 3)   # 整除  → 3
print(10 % 3)    # 取余  → 1
print(10 ** 3)   # 幂运算 → 1000

1.3 常用内置函数

abs(-10)        # 绝对值 → 10
round(3.14, 1)  # 四舍五入 → 3.1
max(1, 3, 5)    # 最大值 → 5
min(1, 3, 5)    # 最小值 → 1
pow(2, 3)       # 幂运算 → 8

注意: Python3 中 true division/)返回浮点数,即使能整除:10 / 2 返回 5.0。要得到整数结果请用 //

二、String(字符串)

Python3 中字符串是 Unicode 字符序列,用引号括起来。

2.1 创建方式

s1 = 'Hello'           # 单引号
s2 = "Hello"           # 双引号
s3 = '''多行
字符串'''              # 三引号(多行)
s4 = """另一种
多行字符串"""

2.2 字符串是不可变的

s = "Hello"
# s[0] = "h"  # ❌ TypeError: 'str' object does not support item assignment

2.3 访问与切片

s = "Hello World"
print(s[0])       # H       — 索引(从 0 开始)
print(s[-1])      # d       — 负索引(从末尾倒数)
print(s[0:5])     # Hello   — 切片 [start:end)
print(s[::2])     # HloWrd  — 步长切片
print(s[::-1])    # dlroW olleH — 反转字符串

2.4 字符串拼接与重复

print("Hello" + " " + "World")  # Hello World(拼接)
print("Ha" * 3)                  # HaHaHa(重复)

2.5 常用方法

s = "  Hello, World!  "

s.upper()          # "  HELLO, WORLD!  "  — 转大写
s.lower()          # "  hello, world!  "  — 转小写
s.strip()          # "Hello, World!"     — 去除两端空白
s.strip().split(",")  # ['Hello', ' World!'] — 按分隔符拆分
",".join(["a", "b", "c"])  # "a,b,c" — 用分隔符连接列表

s.replace("World", "Python")  # "  Hello, Python!  " — 替换
s.find("World")               # 9  — 查找位置(未找到返回 -1)
s.startswith("  Hello")       # True
s.endswith("!")               # True

2.6 格式化

name = "Python"
version = 3

# f-string(推荐)
print(f"{name} {version}")         # Python 3

# format 方法
print("{} {}".format(name, version))  # Python 3

# % 格式化(旧式)
print("%s %d" % (name, version))   # Python 3

三、List(列表)

有序集合,可修改(mutable),用方括号 [] 表示。

3.1 基本操作

fruits = ["apple", "banana", "cherry"]

print(fruits[0])      # apple    — 索引访问
print(fruits[-1])     # cherry   — 负索引
print(fruits[1:3])    # ['banana', 'cherry'] — 切片

3.2 修改与操作

fruits = ["apple", "banana", "cherry"]

# 修改元素
fruits[1] = "blueberry"       # ['apple', 'blueberry', 'cherry']

# 添加
fruits.append("orange")       # 末尾添加一个
fruits.insert(1, "grape")     # 指定位置插入

# 删除
fruits.remove("blueberry")    # 按值删除
fruits.pop(0)                 # 按索引删除并返回
del fruits[0]                 # 按索引删除

# 其他
fruits.sort()                 # 排序(原地)
fruits.reverse()              # 反转
len(fruits)                   # 长度

3.3 列表推导式

squares = [x ** 2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

列表推导式是 Python 的特色语法,简洁高效,建议优先使用。

四、Tuple(元组)

与列表类似,但不可修改(immutable),用圆括号 () 表示。

4.1 基本操作

colors = ("red", "green", "blue")

print(colors[0])       # red
print(colors[1:3])     # ('green', 'blue')
# colors[0] = "yellow" # ❌ TypeError: 'tuple' object does not support item assignment

4.2 特殊语法

# 空元组
empty = ()

# ⚠️ 单元素元组必须加逗号!
single = (50,)     # ✅ 这是元组
not_tuple = (50)   # ❌ 这是整数,不是元组!

print(type(single))   # <class 'tuple'>
print(type(not_tuple)) # <class 'int'>

4.3 元组 vs 列表

特性Tuple(元组)List(列表)
语法(1, 2, 3)[1, 2, 3]
可变性❌ 不可变✅ 可变
速度更快稍慢
哈希✅ 可作为字典的 key❌ 不能作为字典的 key
安全性✅ 不能被意外修改⚠️ 可能被修改

经验法则: 数据不需要修改时优先用 tuple,比如函数返回多个值、字典的 key、配置常量等。

五、Set(集合)

无序、不重复的元素集,用花括号 {}set() 构建。

5.1 创建与去重

# 创建
fruits = {"apple", "banana", "cherry"}
nums = set([1, 2, 2, 3, 3, 4])
print(nums)  # {1, 2, 3, 4}  — 自动去重

# 去重(列表转集合再转回列表)
list_with_dup = [1, 1, 2, 3, 3, 3]
unique = list(set(list_with_dup))
# [1, 2, 3](顺序可能改变)

5.2 集合运算

a = set("abracadabra")
b = set("alacazam")

print(a)          # {'b', 'r', 'a', 'c', 'd'}
print(b)          # {'a', 'l', 'c', 'z', 'm'}

print(a - b)      # 差集 — {'r', 'd', 'b'}(在 a 中但不在 b 中)
print(a | b)      # 并集 — {'a', 'b', 'c', 'd', 'r', 'l', 'z', 'm'}
print(a & b)      # 交集 — {'a', 'c'}
print(a ^ b)      # 对称差集 — {'r', 'd', 'b', 'l', 'z', 'm'}

5.3 常用操作

s = {1, 2, 3}
s.add(4)           # {1, 2, 3, 4} — 添加元素
s.remove(2)        # {1, 3, 4}    — 删除元素(不存在会报错)
s.discard(10)      # 安全删除(不存在也不报错)

print(3 in s)      # True — 判断是否在集合中
print(len(s))      # 3   — 集合大小

5.4 集合推导式

squares = {x ** 2 for x in range(5)}
# {0, 1, 4, 9, 16}

六、Dictionary(字典)

无序的 key:value 键值对集合,用花括号 {} 表示。

6.1 基本操作

# 创建字典
person = {"name": "Alice", "age": 25, "city": "Beijing"}

# 访问
print(person["name"])      # Alice
print(person.get("email", "N/A"))  # N/A(key 不存在返回默认值)

# 修改
person["age"] = 26
person["email"] = "alice@example.com"  # 新增键值对

# 删除
del person["city"]
person.pop("email")

6.2 遍历

person = {"name": "Alice", "age": 25, "city": "Beijing"}

# 遍历 key
for key in person:
    print(key)

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

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

6.3 常用方法

d = {"a": 1, "b": 2}

d.keys()          # dict_keys(['a', 'b'])
d.values()        # dict_values([1, 2])
d.items()         # dict_items([('a', 1), ('b', 2)])
d.get("c", 0)     # 0(key 不存在返回默认值)
d.update({"c": 3, "d": 4})  # 批量添加/更新
d.setdefault("e", 5)        # 如果 key 不存在则设置默认值

6.4 字典推导式

squares = {x: x ** 2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

注意: 字典的 key 必须是不可变类型(字符串、数字、元组),不能是 list 或 dict。

七、类型检查与转换

7.1 类型检查

x = 42
print(type(x))               # <class 'int'>
print(isinstance(x, int))    # True
print(isinstance(x, float))  # False

type()isinstance() 的区别:

class Dog(Animal):
    pass

d = Dog()
type(d) == Animal          # ❌ False(精确匹配)
isinstance(d, Animal)      # ✅ True(考虑继承关系)

7.2 类型转换

int("42")       # 42        — 字符串转整数
float("3.14")   # 3.14      — 字符串转浮点数
str(100)        # "100"     — 数字转字符串

list("abc")     # ['a', 'b', 'c']  — 字符串转列表
tuple([1,2,3])  # (1, 2, 3)         — 列表转元组
set([1,1,2])    # {1, 2}            — 列表转集合(去重)

dict([("a", 1), ("b", 2)])  # {'a': 1, 'b': 2} — 键值对列表转字典

八、多变量赋值

# 同时赋值
a, b, c = 1, 2, "hello"

# 多个变量指向同一值
a = b = c = 0

# 交换变量(Python 独有的优雅写法)
a, b = b, a

九、删除变量

x = 10
del x
# print(x)  # ❌ NameError: name 'x' is not defined