跳转至

Python 数据类型详解

Python 是一门动态类型语言,拥有丰富的内置数据类型。了解这些数据类型是掌握 Python 编程的基础。

基本数据类型

1. 数字类型 (Numeric Types)

整数 (int)

# 整数类型
age = 25
count = -10
big_number = 123456789

浮点数 (float)

# 浮点数类型
price = 99.99
temperature = -3.5
scientific = 1.5e-3  # 科学计数法,等于0.0015

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

复数 (complex)

# 复数类型
z1 = 3 + 4j
z2 = complex(3, 4)   # 另一种创建方式

print(z1.real)       # 实部: 3.0
print(z1.imag)       # 虚部: 4.0

2. 字符串类型 (str)

# 字符串的不同定义方式
name = "Alice"
message = 'Hello World'
multiline = """这是一个
多行字符串"""

# 字符串是不可变的
greeting = "Hello"
# greeting[0] = "h"  # 这会报错

# 字符串操作
print(len(name))          # 长度: 5
print(name.upper())       # 大写: ALICE
print(name.lower())       # 小写: alice
print("A" in name)        # 包含检查: True

# 字符串格式化
age = 25
formatted = f"我今年{age}岁"  # f-string
old_style = "我今年%d岁" % age
new_style = "我今年{}岁".format(age)

3. 布尔类型 (bool)

# 布尔值
is_active = True
is_complete = False

print(type(is_active))    # <class 'bool'>

# 真值测试
print(bool(1))           # True
print(bool(0))           # False
print(bool("hello"))     # True
print(bool(""))          # False
print(bool([]))          # False
print(bool([1, 2]))      # True

集合数据类型

1. 列表 (list)

# 列表是可变的有序集合
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]

# 列表操作
fruits.append("orange")      # 添加元素
fruits.insert(1, "grape")    # 在指定位置插入
fruits.remove("banana")      # 删除元素
popped = fruits.pop()        # 弹出最后一个元素

# 列表推导式
squares = [x**2 for x in range(10)]
even_squares = [x**2 for x in range(10) if x % 2 == 0]

print(fruits)                # ['apple', 'grape', 'cherry', 'orange']
print(squares)               # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

2. 元组 (tuple)

# 元组是不可变的有序集合
coordinates = (10, 20)
rgb = (255, 128, 0)
single_item = (42,)          # 单元素元组需要逗号

# 元组解包
x, y = coordinates
print(f"x={x}, y={y}")       # x=10, y=20

# 命名元组
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print(p.x, p.y)             # 10 20

3. 字典 (dict)

# 字典是可变的键值对集合
person = {
    "name": "Alice",
    "age": 25,
    "city": "Beijing"
}

# 字典操作
person["email"] = "alice@email.com"    # 添加键值对
person.update({"phone": "123456789"})  # 批量更新
del person["city"]                     # 删除键值对

# 字典方法
print(person.keys())        # 获取所有键
print(person.values())      # 获取所有值
print(person.items())       # 获取所有键值对

# 字典推导式
squares_dict = {x: x**2 for x in range(5)}
print(squares_dict)         # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

4. 集合 (set)

# 集合是可变的无序不重复元素集合
fruits = {"apple", "banana", "cherry"}
numbers = {1, 2, 3, 4, 5}

# 集合操作
fruits.add("orange")         # 添加元素
fruits.remove("banana")      # 删除元素
fruits.discard("grape")      # 删除元素(不存在时不报错)

# 集合运算
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

union = set1 | set2          # 并集: {1, 2, 3, 4, 5, 6}
intersection = set1 & set2   # 交集: {3, 4}
difference = set1 - set2     # 差集: {1, 2}

# 冻结集合 (frozenset)
frozen = frozenset([1, 2, 3])  # 不可变集合

特殊数据类型

1. None 类型

# None 表示空值或缺失值
result = None
data = [1, 2, None, 4]

def get_user(id):
    if id > 0:
        return {"name": "Alice"}
    return None

user = get_user(-1)
if user is None:
    print("用户不存在")

2. 字节类型

# bytes - 不可变字节序列
text = "Hello"
encoded = text.encode('utf-8')
print(type(encoded))         # <class 'bytes'>

# bytearray - 可变字节序列
mutable_bytes = bytearray(b"Hello")
mutable_bytes[0] = ord('h')
print(mutable_bytes)         # bytearray(b'hello')

类型检查和转换

类型检查

# 使用 type() 检查类型
x = 42
print(type(x))               # <class 'int'>
print(type(x) == int)        # True

# 使用 isinstance() 检查类型(推荐)
print(isinstance(x, int))    # True
print(isinstance(x, (int, float)))  # 检查多种类型

类型转换

# 显式类型转换
num_str = "123"
num_int = int(num_str)       # 字符串转整数
num_float = float(num_str)   # 字符串转浮点数

# 转换为字符串
age = 25
age_str = str(age)

# 转换为列表
text = "hello"
char_list = list(text)       # ['h', 'e', 'l', 'l', 'o']

# 转换为集合(去重)
numbers = [1, 2, 2, 3, 3, 3]
unique = set(numbers)        # {1, 2, 3}

总结

Python 提供了丰富的内置数据类型,每种类型都有其特定的用途:

  • 数字类型:用于数学计算
  • 字符串:用于文本处理
  • 列表:用于存储有序的可变数据
  • 元组:用于存储有序的不可变数据
  • 字典:用于存储键值对映射
  • 集合:用于存储唯一元素
  • 布尔值:用于逻辑判断

掌握这些数据类型的特性和使用方法,是编写高效 Python 代码的基础。在实际开发中,选择合适的数据类型不仅能提高代码的可读性,还能优化程序的性能。

回到页面顶部