Skip to content

Python 基本数据类型

Python 中的基本数据类型可以分为以下几类:数字类型字符串布尔类型列表元组字典集合空值类型

1. 数字类型(Number)

1.1 整数(int)

Python 的整数没有大小限制,可以表示任意大的整数。

python
# 整数
a = 10
b = -5
c = 0

print(type(a))  # <class 'int'>
print(a + b)    # 5
print(a * b)    # -50

# Python 整数可以非常大
big_num = 10 ** 100
print(big_num)  # 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

# 不同进制表示
binary = 0b1010      # 二进制
octal = 0o12         # 八进制
hexadecimal = 0xA    # 十六进制

print(binary)        # 10
print(octal)         # 10
print(hexadecimal)   # 10

1.2 浮点数(float)

浮点数用于表示小数,遵循 IEEE 754 双精度标准。

python
# 浮点数
f1 = 3.14
f2 = -0.5
f3 = 1.0

print(type(f1))  # <class 'float'>

# 科学计数法
f4 = 1.5e2    # 1.5 × 10²
f5 = 3e-3     # 3 × 10⁻³

print(f4)  # 150.0
print(f5)  # 0.003

# ⚠️ 浮点数精度问题
print(0.1 + 0.2)          # 0.30000000000000004
print(0.1 + 0.2 == 0.3)   # False

# 使用 round() 或 decimal 模块解决精度问题
print(round(0.1 + 0.2, 1))  # 0.3

from decimal import Decimal
print(Decimal('0.1') + Decimal('0.2'))  # 0.3

1.3 复数(complex)

复数由实部和虚部组成,虚部用 jJ 表示。

python
# 复数
c1 = 3 + 4j
c2 = complex(1, 2)  # 1 + 2j

print(type(c1))    # <class 'complex'>
print(c1.real)     # 3.0  (实部)
print(c1.imag)     # 4.0  (虚部)
print(c1 + c2)     # (4+6j)
print(abs(c1))     # 5.0  (模:√(3² + 4²))

1.4 数字类型转换

python
# 类型转换
print(int(3.9))       # 3      (截断小数,不是四舍五入)
print(int("42"))      # 42     (字符串转整数)
print(float(10))      # 10.0
print(float("3.14"))  # 3.14
print(complex(3))     # (3+0j)

# 常用数学运算
print(10 / 3)    # 3.3333333333333335  (真除法)
print(10 // 3)   # 3                   (整除/地板除)
print(10 % 3)    # 1                   (取余)
print(2 ** 10)   # 1024                (幂运算)

# 内置数学函数
print(abs(-7))       # 7
print(max(1, 5, 3))  # 5
print(min(1, 5, 3))  # 1
print(divmod(10, 3)) # (3, 1)  (同时返回商和余数)

2. 字符串(str)

字符串是不可变的 Unicode 字符序列。

2.1 创建字符串

python
# 单引号、双引号、三引号
s1 = 'hello'
s2 = "world"
s3 = '''多行
字符串'''
s4 = """也是
多行字符串"""

print(type(s1))  # <class 'str'>
print(s3)
# 多行
# 字符串

# 转义字符
print("hello\tworld")    # hello	world
print("hello\nworld")    # hello(换行)world
print("路径:C:\\Users")   # 路径:C:\Users

# 原始字符串(忽略转义)
print(r"C:\new\test")    # C:\new\test

2.2 字符串索引与切片

python
s = "Hello, Python!"

# 索引(从 0 开始,支持负索引)
print(s[0])     # H
print(s[-1])    # !
print(s[7])     # P

# 切片 [start:end:step],左闭右开
print(s[0:5])    # Hello
print(s[7:])     # Python!
print(s[:5])     # Hello
print(s[::2])    # Hlo yhn
print(s[::-1])   # !nohtyP ,olleH  (反转字符串)

2.3 常用字符串方法

python
s = "  Hello, World!  "

# 大小写转换
print(s.upper())        # "  HELLO, WORLD!  "
print(s.lower())        # "  hello, world!  "
print(s.title())        # "  Hello, World!  "
print(s.capitalize())   # "  hello, world!  "
print(s.swapcase())     # "  hELLO, wORLD!  "

# 去除空白
print(s.strip())    # "Hello, World!"
print(s.lstrip())   # "Hello, World!  "
print(s.rstrip())   # "  Hello, World!"

# 查找与替换
text = "Hello, Python! Hello, World!"
print(text.find("Hello"))       # 0   (返回首次出现的索引)
print(text.find("Java"))        # -1  (未找到返回 -1)
print(text.count("Hello"))      # 2   (出现次数)
print(text.replace("Hello", "Hi"))  # "Hi, Python! Hi, World!"

# 分割与拼接
csv = "apple,banana,cherry"
fruits = csv.split(",")
print(fruits)                   # ['apple', 'banana', 'cherry']
print(" | ".join(fruits))       # "apple | banana | cherry"

# 判断方法
print("abc123".isalnum())    # True  (字母或数字)
print("abc".isalpha())       # True  (纯字母)
print("123".isdigit())       # True  (纯数字)
print("hello".islower())     # True
print("HELLO".isupper())     # True
print("  ".isspace())        # True
print("Hello".startswith("He"))  # True
print("Hello".endswith("lo"))    # True

2.4 字符串格式化

python
name = "Alice"
age = 25
score = 95.5

# 1. f-string(推荐,Python 3.6+)
print(f"我叫{name},今年{age}岁")           # 我叫Alice,今年25岁
print(f"成绩:{score:.1f}")                 # 成绩:95.5
print(f"十六进制:{255:#x}")                # 十六进制:0xff
print(f"{'居中':=^20}")                     # ========居中========

# 2. format() 方法
print("{}今年{}岁".format(name, age))       # Alice今年25岁
print("{1}今年{0}岁".format(age, name))     # Alice今年25岁
print("{n}今年{a}岁".format(n=name, a=age)) # Alice今年25岁

# 3. % 格式化(旧式)
print("我叫%s,今年%d岁" % (name, age))     # 我叫Alice,今年25岁
print("圆周率约为%.2f" % 3.14159)           # 圆周率约为3.14

3. 布尔类型(bool)

布尔类型是 int 的子类,只有 True(1)和 False(0)两个值。

python
# 布尔值
t = True
f = False

print(type(t))       # <class 'bool'>
print(isinstance(t, int))  # True  (bool 是 int 的子类)

# 布尔运算
print(True and False)   # False
print(True or False)    # True
print(not True)         # False

# True/False 可以参与数值运算
print(True + True)   # 2
print(True * 10)     # 10
print(False + 1)     # 1

# 假值(Falsy)—— 以下值在布尔上下文中为 False
print(bool(0))        # False
print(bool(0.0))      # False
print(bool(""))       # False  (空字符串)
print(bool([]))       # False  (空列表)
print(bool(()))       # False  (空元组)
print(bool({}))       # False  (空字典)
print(bool(set()))    # False  (空集合)
print(bool(None))     # False

# 真值(Truthy)—— 非零、非空的值为 True
print(bool(1))        # True
print(bool(-1))       # True
print(bool("hello"))  # True
print(bool([1, 2]))   # True

# 比较运算返回布尔值
print(3 > 2)      # True
print(3 == 2)      # False
print(3 != 2)      # True
print(1 <= 1)      # True

# 链式比较
x = 5
print(1 < x < 10)    # True  (等价于 1 < x and x < 10)
print(1 < x > 3)     # True

4. 列表(list)

列表是有序、可变的序列,可以存储任意类型的元素。

4.1 创建列表

python
# 创建列表
list1 = [1, 2, 3, 4, 5]
list2 = ["a", "b", "c"]
list3 = [1, "hello", True, 3.14, [1, 2]]  # 可以混合类型
list4 = list()         # 空列表
list5 = list("hello")  # ['h', 'e', 'l', 'l', 'o']
list6 = list(range(5)) # [0, 1, 2, 3, 4]

print(type(list1))  # <class 'list'>
print(len(list1))   # 5

4.2 列表索引与切片

python
nums = [10, 20, 30, 40, 50]

# 索引
print(nums[0])     # 10
print(nums[-1])    # 50

# 切片(与字符串相同)
print(nums[1:3])   # [20, 30]
print(nums[::-1])  # [50, 40, 30, 20, 10]

# 修改元素
nums[0] = 100
print(nums)  # [100, 20, 30, 40, 50]

# 切片赋值
nums[1:3] = [200, 300]
print(nums)  # [100, 200, 300, 40, 50]

4.3 列表常用方法

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

# 添加元素
fruits.append("cherry")         # 末尾追加
print(fruits)                   # ['apple', 'banana', 'cherry']

fruits.insert(1, "blueberry")   # 指定位置插入
print(fruits)                   # ['apple', 'blueberry', 'banana', 'cherry']

fruits.extend(["date", "fig"])  # 扩展列表
print(fruits)                   # ['apple', 'blueberry', 'banana', 'cherry', 'date', 'fig']

# 删除元素
fruits.remove("blueberry")     # 按值删除(只删第一个匹配)
print(fruits)                  # ['apple', 'banana', 'cherry', 'date', 'fig']

popped = fruits.pop()          # 弹出末尾元素
print(popped)                  # fig
print(fruits)                  # ['apple', 'banana', 'cherry', 'date']

popped = fruits.pop(1)         # 弹出指定索引
print(popped)                  # banana

del fruits[0]                  # 按索引删除
print(fruits)                  # ['cherry', 'date']

# 排序
nums = [3, 1, 4, 1, 5, 9, 2, 6]
nums.sort()                    # 原地升序排序
print(nums)                    # [1, 1, 2, 3, 4, 5, 6, 9]

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

sorted_nums = sorted([3, 1, 2])  # 返回新列表,不修改原列表
print(sorted_nums)                # [1, 2, 3]

# 其他方法
nums = [1, 2, 3, 2, 1]
print(nums.count(2))     # 2      (统计出现次数)
print(nums.index(3))     # 2      (返回首次出现的索引)
nums.reverse()           # 原地反转
print(nums)              # [1, 2, 3, 2, 1]

4.4 列表推导式

python
# 基本推导式
squares = [x ** 2 for x in range(1, 6)]
print(squares)  # [1, 4, 9, 16, 25]

# 带条件的推导式
evens = [x for x in range(10) if x % 2 == 0]
print(evens)  # [0, 2, 4, 6, 8]

# 嵌套推导式
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
print(flat)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

# 带条件表达式的推导式
labels = ["偶数" if x % 2 == 0 else "奇数" for x in range(5)]
print(labels)  # ['偶数', '奇数', '偶数', '奇数', '偶数']

5. 元组(tuple)

元组是有序、不可变的序列。一旦创建就不能修改。

python
# 创建元组
t1 = (1, 2, 3)
t2 = ("a", "b", "c")
t3 = tuple([1, 2, 3])   # 从列表转换
t4 = ()                  # 空元组
t5 = (42,)               # ⚠️ 单元素元组必须加逗号

print(type(t1))  # <class 'tuple'>

# ⚠️ 注意:没有逗号不是元组
not_tuple = (42)
print(type(not_tuple))  # <class 'int'>

# 索引与切片(与列表相同)
print(t1[0])      # 1
print(t1[-1])     # 3
print(t1[1:])     # (2, 3)

# 元组不可变
# t1[0] = 10  # ❌ TypeError: 'tuple' object does not support item assignment

# 元组方法
t = (1, 2, 3, 2, 1)
print(t.count(2))   # 2
print(t.index(3))   # 2

# 元组拆包
a, b, c = (10, 20, 30)
print(a, b, c)  # 10 20 30

# 使用 * 收集剩余元素
first, *rest = (1, 2, 3, 4, 5)
print(first)  # 1
print(rest)   # [2, 3, 4, 5]

# 交换变量(本质是元组拆包)
x, y = 1, 2
x, y = y, x
print(x, y)  # 2 1

# 元组 vs 列表
# 1. 元组不可变,更安全
# 2. 元组可以作为字典的 key,列表不行
# 3. 元组占用更少的内存
import sys
print(sys.getsizeof([1, 2, 3]))   # 88(列表)
print(sys.getsizeof((1, 2, 3)))   # 64(元组)

6. 字典(dict)

字典是键值对的无序集合(Python 3.7+ 保持插入顺序),键必须是不可变类型。

6.1 创建字典

python
# 创建字典
d1 = {"name": "Alice", "age": 25, "city": "Beijing"}
d2 = dict(name="Bob", age=30)
d3 = dict([("a", 1), ("b", 2)])
d4 = {}          # 空字典
d5 = dict()      # 空字典

# 使用 fromkeys 创建
d6 = dict.fromkeys(["a", "b", "c"], 0)
print(d6)  # {'a': 0, 'b': 0, 'c': 0}

print(type(d1))  # <class 'dict'>
print(len(d1))   # 3

6.2 访问与修改

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

# 访问
print(person["name"])          # Alice
# print(person["email"])       # ❌ KeyError

print(person.get("name"))      # Alice
print(person.get("email"))     # None  (不存在返回 None)
print(person.get("email", "未设置"))  # 未设置  (指定默认值)

# 修改 / 添加
person["age"] = 26              # 修改已有键
person["email"] = "a@test.com"  # 添加新键
print(person)  # {'name': 'Alice', 'age': 26, 'city': 'Beijing', 'email': 'a@test.com'}

# update 批量更新
person.update({"age": 27, "phone": "123"})
print(person)  # {'name': 'Alice', 'age': 27, 'city': 'Beijing', 'email': 'a@test.com', 'phone': '123'}

# 删除
del person["phone"]
print(person)  # {'name': 'Alice', 'age': 27, 'city': 'Beijing', 'email': 'a@test.com'}

popped = person.pop("email")
print(popped)   # a@test.com

last = person.popitem()  # 弹出最后一个键值对
print(last)     # ('city', 'Beijing')

6.3 字典遍历

python
scores = {"Alice": 90, "Bob": 85, "Charlie": 92}

# 遍历键
for name in scores:
    print(name, end=" ")         # Alice Bob Charlie
print()

# 遍历值
for score in scores.values():
    print(score, end=" ")        # 90 85 92
print()

# 遍历键值对
for name, score in scores.items():
    print(f"{name}: {score}")
# Alice: 90
# Bob: 85
# Charlie: 92

# 检查键是否存在
print("Alice" in scores)     # True
print("David" in scores)     # False
print("Alice" not in scores) # False

6.4 字典推导式

python
# 基本推导式
squares = {x: x ** 2 for x in range(1, 6)}
print(squares)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# 带条件
even_squares = {x: x ** 2 for x in range(1, 6) if x % 2 == 0}
print(even_squares)  # {2: 4, 4: 16}

# 反转键值
original = {"a": 1, "b": 2, "c": 3}
reversed_dict = {v: k for k, v in original.items()}
print(reversed_dict)  # {1: 'a', 2: 'b', 3: 'c'}

7. 集合(set)

集合是无序、不重复的元素集,支持数学集合运算。

7.1 创建集合

python
# 创建集合
s1 = {1, 2, 3, 4, 5}
s2 = set([1, 2, 2, 3, 3])  # 自动去重
s3 = set("hello")           # {'h', 'e', 'l', 'o'}
s4 = set()                   # 空集合(不能用 {},那是空字典)

print(type(s1))  # <class 'set'>
print(s2)        # {1, 2, 3}
print(s3)        # {'l', 'o', 'e', 'h'}  (无序)

# 集合元素必须是不可变类型
# s = {[1, 2]}  # ❌ TypeError: unhashable type: 'list'
s = {(1, 2), "hello", 42}  # ✅ 元组、字符串、数字可以

7.2 集合操作

python
s = {1, 2, 3}

# 添加
s.add(4)
print(s)  # {1, 2, 3, 4}

s.update([5, 6])
print(s)  # {1, 2, 3, 4, 5, 6}

# 删除
s.remove(6)     # 删除指定元素,不存在则报错
s.discard(10)   # 删除指定元素,不存在不报错
popped = s.pop() # 随机弹出一个元素
print(s)

s.clear()       # 清空集合
print(s)        # set()

7.3 集合运算

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

# 并集
print(a | b)           # {1, 2, 3, 4, 5, 6, 7, 8}
print(a.union(b))      # {1, 2, 3, 4, 5, 6, 7, 8}

# 交集
print(a & b)               # {4, 5}
print(a.intersection(b))   # {4, 5}

# 差集
print(a - b)               # {1, 2, 3}
print(a.difference(b))     # {1, 2, 3}

# 对称差集(在 a 或 b 中,但不同时在两者中)
print(a ^ b)                       # {1, 2, 3, 6, 7, 8}
print(a.symmetric_difference(b))   # {1, 2, 3, 6, 7, 8}

# 子集与超集
c = {1, 2}
print(c.issubset(a))      # True   (c 是 a 的子集)
print(a.issuperset(c))    # True   (a 是 c 的超集)
print(a.isdisjoint(b))    # False  (a 和 b 有交集)

# 集合推导式
s = {x ** 2 for x in range(1, 6)}
print(s)  # {1, 4, 9, 16, 25}

# 常见用途:列表去重
nums = [1, 3, 2, 3, 1, 4, 2]
unique = list(set(nums))
print(unique)  # [1, 2, 3, 4]  (顺序可能不同)

7.4 不可变集合(frozenset)

python
# frozenset 不可修改,可以作为字典的键或集合的元素
fs = frozenset([1, 2, 3])
print(fs)           # frozenset({1, 2, 3})
# fs.add(4)         # ❌ AttributeError

# 可以作为字典的键
d = {fs: "value"}
print(d)  # {frozenset({1, 2, 3}): 'value'}

8. 空值类型(NoneType)

None 是 Python 的空值,表示"没有值"。

python
x = None

print(type(x))       # <class 'NoneType'>
print(x is None)     # True  (推荐用 is 判断)
print(x == None)     # True  (不推荐用 == 判断)

# 常见用法
# 1. 函数默认返回值
def greet(name):
    print(f"Hello, {name}")

result = greet("Alice")  # Hello, Alice
print(result)             # None

# 2. 默认参数
def add_item(item, lst=None):
    if lst is None:
        lst = []
    lst.append(item)
    return lst

print(add_item(1))       # [1]
print(add_item(2))       # [2]  (每次调用创建新列表)

# 3. 占位 / 初始化
data = None
# ... 后续赋值
data = [1, 2, 3]

9. 类型检查与转换

9.1 类型检查

python
x = 42

# type() —— 返回精确类型
print(type(x))              # <class 'int'>
print(type(x) == int)       # True

# isinstance() —— 支持继承关系检查(推荐)
print(isinstance(x, int))          # True
print(isinstance(x, (int, float))) # True  (可以传入元组检查多个类型)
print(isinstance(True, int))       # True  (bool 是 int 的子类)

9.2 类型转换

python
# 转整数
print(int("42"))       # 42
print(int(3.99))       # 3   (截断,不是四舍五入)
print(int("0xff", 16)) # 255 (指定进制)
print(int("0b1010", 2))# 10
print(int(True))       # 1

# 转浮点数
print(float("3.14"))   # 3.14
print(float(10))       # 10.0
print(float("inf"))    # inf  (正无穷)

# 转字符串
print(str(42))         # "42"
print(str(3.14))       # "3.14"
print(str([1, 2, 3]))  # "[1, 2, 3]"
print(str(True))       # "True"

# 转列表
print(list("hello"))       # ['h', 'e', 'l', 'l', 'o']
print(list((1, 2, 3)))     # [1, 2, 3]
print(list({1, 2, 3}))     # [1, 2, 3]
print(list(range(5)))      # [0, 1, 2, 3, 4]

# 转元组
print(tuple([1, 2, 3]))    # (1, 2, 3)
print(tuple("abc"))        # ('a', 'b', 'c')

# 转集合
print(set([1, 2, 2, 3]))   # {1, 2, 3}
print(set("hello"))        # {'h', 'e', 'l', 'o'}

# 转字典(需要键值对序列)
print(dict([("a", 1), ("b", 2)]))  # {'a': 1, 'b': 2}
print(dict(zip("abc", [1, 2, 3]))) # {'a': 1, 'b': 2, 'c': 3}

# 转布尔
print(bool(0))    # False
print(bool(42))   # True
print(bool(""))   # False
print(bool("hi")) # True

10. 总结对比

类型关键字有序可变可重复示例
整数int---42
浮点数float---3.14
复数complex---3+4j
字符串str"hello"
布尔bool---True / False
列表list[1, 2, 3]
元组tuple(1, 2, 3)
字典dict键不可重复{"a": 1}
集合set{1, 2, 3}
冻结集合frozensetfrozenset({1, 2})
空值NoneType---None

*Python 3.7+ 字典保持插入顺序

可变 vs 不可变

python
# 不可变类型:int, float, str, tuple, frozenset, bool, None
# 可变类型:list, dict, set

# 不可变类型 → 修改会创建新对象
a = "hello"
b = a
a = a + " world"
print(a)  # hello world
print(b)  # hello  (b 不受影响)

# 可变类型 → 修改会影响所有引用
a = [1, 2, 3]
b = a          # b 和 a 指向同一个列表
a.append(4)
print(a)  # [1, 2, 3, 4]
print(b)  # [1, 2, 3, 4]  (b 也变了!)

# 要创建独立副本,使用 copy
a = [1, 2, 3]
b = a.copy()   # 或 b = a[:]  或 b = list(a)
a.append(4)
print(a)  # [1, 2, 3, 4]
print(b)  # [1, 2, 3]  (b 不受影响)

# 嵌套结构需要深拷贝
import copy
a = [[1, 2], [3, 4]]
b = copy.deepcopy(a)
a[0].append(5)
print(a)  # [[1, 2, 5], [3, 4]]
print(b)  # [[1, 2], [3, 4]]  (b 不受影响)

Released under the MIT License.