HiHuo
首页
博客
手册
工具
关于
首页
博客
手册
工具
关于
  • Python 新手入门教程

    • Python新手入门教程 - 零基础学Python,8章+HTTP服务实战 | HiHuo
    • Python简介与环境搭建 - 安装配置Python开发环境 | HiHuo
    • Python基础语法 - 缩进、变量、注释、输入输出 | HiHuo
    • Python数据类型详解 - 字符串、列表、字典、元组 | HiHuo
    • Python流程控制 - if条件判断、for/while循环 | HiHuo
    • Python函数与模块 - 定义函数、参数传递、模块导入 | HiHuo
    • Python面向对象编程 - 类、对象、继承、多态 | HiHuo
    • Python文件与异常处理 - 读写文件、try/except异常捕获 | HiHuo
    • Python HTTP服务项目实战 - 构建待办事项API服务 | HiHuo

数据类型详解

Python 有丰富的内置数据类型,本章详细讲解常用的数据类型。

数据类型概览

┌─────────────────────────────────────────────────────────┐
│                   Python 数据类型                        │
├─────────────┬──────────────┬────────────────────────────┤
│  数值类型   │   序列类型    │        映射/集合           │
│  int        │   str        │        dict               │
│  float      │   list       │        set                │
│  bool       │   tuple      │        frozenset          │
│  complex    │   range      │                           │
└─────────────┴──────────────┴────────────────────────────┘

数值类型

整数 (int)

# 整数可以很大,没有大小限制
a = 100
b = -50
c = 123456789012345678901234567890

# 不同进制表示
binary = 0b1010      # 二进制: 10
octal = 0o17         # 八进制: 15
hexadecimal = 0xff   # 十六进制: 255

# 数字分隔符(提高可读性)
money = 1_000_000    # 等于 1000000

浮点数 (float)

# 小数
price = 19.99
pi = 3.14159

# 科学计数法
distance = 1.5e11    # 1.5 × 10^11
tiny = 1e-6          # 0.000001

# 浮点数精度问题
print(0.1 + 0.2)     # 0.30000000000000004

# 解决精度问题:使用 Decimal
from decimal import Decimal
print(Decimal('0.1') + Decimal('0.2'))  # 0.3

布尔值 (bool)

is_active = True
is_deleted = False

# 布尔值本质是整数
print(True + True)   # 2
print(False + 1)     # 1

# 以下值被视为 False
# False, None, 0, 0.0, '', [], {}, set()

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

字符串 (str)

字符串是最常用的数据类型之一。

创建字符串

# 单引号和双引号等效
s1 = 'Hello'
s2 = "World"

# 三引号:多行字符串
s3 = """这是
一个多行
字符串"""

# 原始字符串:忽略转义
path = r"C:\Users\name\Documents"

# 转义字符
print("Hello\nWorld")   # 换行
print("Hello\tWorld")   # Tab
print("He said \"Hi\"") # 引号

字符串索引与切片

s = "Hello, Python!"

# 索引(从0开始)
print(s[0])      # H
print(s[7])      # P
print(s[-1])     # !(倒数第一个)
print(s[-6])     # y

# 切片 [start:end:step]
print(s[0:5])    # Hello(不包含end)
print(s[7:])     # Python!
print(s[:5])     # Hello
print(s[::2])    # Hlo yhn(步长2)
print(s[::-1])   # !nohtyP ,olleH(反转)

字符串常用方法

s = "  Hello, Python!  "

# 大小写转换
print(s.upper())         # "  HELLO, PYTHON!  "
print(s.lower())         # "  hello, python!  "
print(s.title())         # "  Hello, Python!  "
print(s.capitalize())    # "  hello, python!  "

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

# 查找和替换
text = "Hello, World!"
print(text.find("World"))    # 7(返回索引)
print(text.find("Python"))   # -1(未找到)
print(text.replace("World", "Python"))  # "Hello, Python!"

# 分割和连接
csv = "apple,banana,orange"
fruits = csv.split(",")       # ['apple', 'banana', 'orange']
print("-".join(fruits))       # "apple-banana-orange"

# 判断方法
print("123".isdigit())   # True
print("abc".isalpha())   # True
print("abc123".isalnum())# True
print("Hello".startswith("He"))  # True
print("Hello".endswith("lo"))    # True

典型案例:文本处理

# 处理用户输入的邮箱
email = "  User@Example.COM  "
clean_email = email.strip().lower()
print(f"处理后的邮箱: {clean_email}")

# 提取文件名
path = "/home/user/documents/report.pdf"
filename = path.split("/")[-1]
name, ext = filename.rsplit(".", 1)
print(f"文件名: {name}, 扩展名: {ext}")

列表 (list)

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

创建列表

# 创建列表
numbers = [1, 2, 3, 4, 5]
fruits = ["苹果", "香蕉", "橙子"]
mixed = [1, "hello", 3.14, True, [1, 2]]

# 空列表
empty = []
empty = list()

# 从字符串创建
chars = list("Hello")  # ['H', 'e', 'l', 'l', 'o']

# 列表生成式
squares = [x**2 for x in range(1, 6)]  # [1, 4, 9, 16, 25]
evens = [x for x in range(10) if x % 2 == 0]  # [0, 2, 4, 6, 8]

列表索引与切片

fruits = ["苹果", "香蕉", "橙子", "葡萄", "西瓜"]

# 索引
print(fruits[0])     # 苹果
print(fruits[-1])    # 西瓜

# 切片
print(fruits[1:3])   # ['香蕉', '橙子']
print(fruits[:3])    # ['苹果', '香蕉', '橙子']
print(fruits[2:])    # ['橙子', '葡萄', '西瓜']
print(fruits[::2])   # ['苹果', '橙子', '西瓜']

# 修改元素
fruits[0] = "芒果"
print(fruits)        # ['芒果', '香蕉', '橙子', '葡萄', '西瓜']

列表常用方法

fruits = ["苹果", "香蕉"]

# 添加元素
fruits.append("橙子")          # 末尾添加
fruits.insert(0, "芒果")       # 指定位置插入
fruits.extend(["葡萄", "西瓜"]) # 扩展列表

# 删除元素
fruits.remove("香蕉")          # 删除指定值
last = fruits.pop()            # 弹出最后一个
first = fruits.pop(0)          # 弹出指定位置
del fruits[0]                  # 删除指定位置

# 查找和统计
numbers = [1, 2, 3, 2, 4, 2]
print(numbers.index(2))        # 1(第一个2的索引)
print(numbers.count(2))        # 3(2出现的次数)

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

# 反转
numbers.reverse()              # 原地反转

# 复制
copy1 = numbers.copy()         # 浅拷贝
copy2 = numbers[:]             # 切片拷贝

典型案例:学生成绩管理

# 学生成绩列表
scores = [85, 92, 78, 90, 88, 76, 95]

# 基本统计
print(f"总人数: {len(scores)}")
print(f"最高分: {max(scores)}")
print(f"最低分: {min(scores)}")
print(f"平均分: {sum(scores) / len(scores):.2f}")

# 及格人数
passed = [s for s in scores if s >= 60]
print(f"及格人数: {len(passed)}")

# 成绩排名
sorted_scores = sorted(scores, reverse=True)
print(f"成绩排名: {sorted_scores}")

元组 (tuple)

元组是有序、不可变的集合。

# 创建元组
point = (3, 4)
colors = ("red", "green", "blue")
single = (1,)          # 单元素元组必须有逗号
empty = ()

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

# 多重赋值实际是元组
a, b, c = 1, 2, 3

# 元组不可变
# colors[0] = "yellow"  # TypeError!

# 但元组内的可变对象可以修改
mixed = (1, [2, 3], 4)
mixed[1].append(5)
print(mixed)           # (1, [2, 3, 5], 4)

元组 vs 列表:

  • 元组不可变,更安全
  • 元组可以作为字典的键
  • 元组性能略优于列表
  • 通常用于表示固定的数据集

字典 (dict)

字典是键值对的集合,无序(Python 3.7+ 保持插入顺序)。

创建字典

# 创建字典
person = {
    "name": "张三",
    "age": 25,
    "city": "北京"
}

# 其他创建方式
d1 = dict(name="李四", age=30)
d2 = dict([("a", 1), ("b", 2)])
d3 = {x: x**2 for x in range(5)}  # 字典推导式

字典操作

person = {"name": "张三", "age": 25}

# 访问元素
print(person["name"])         # 张三
print(person.get("city"))     # None(不存在时返回None)
print(person.get("city", "未知"))  # 未知(指定默认值)

# 添加/修改元素
person["city"] = "北京"
person["age"] = 26
person.update({"email": "test@example.com"})

# 删除元素
del person["email"]
city = person.pop("city")     # 弹出并返回值
person.popitem()              # 弹出最后一个键值对

# 遍历字典
for key in person:
    print(key, person[key])

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 存在")

典型案例:学生信息系统

# 学生信息字典
students = {
    "001": {"name": "张三", "age": 20, "scores": [85, 90, 78]},
    "002": {"name": "李四", "age": 21, "scores": [92, 88, 95]},
    "003": {"name": "王五", "age": 19, "scores": [76, 82, 80]}
}

# 查询学生信息
def get_student(student_id):
    student = students.get(student_id)
    if student:
        avg = sum(student["scores"]) / len(student["scores"])
        print(f"姓名: {student['name']}")
        print(f"年龄: {student['age']}")
        print(f"平均分: {avg:.2f}")
    else:
        print("学生不存在")

get_student("001")

# 添加新学生
students["004"] = {"name": "赵六", "age": 22, "scores": [88, 91, 86]}

集合 (set)

集合是无序、不重复的元素集合。

# 创建集合
fruits = {"苹果", "香蕉", "橙子"}
numbers = set([1, 2, 2, 3, 3, 3])  # {1, 2, 3}

# 集合操作
fruits.add("葡萄")
fruits.remove("香蕉")       # 不存在会报错
fruits.discard("芒果")      # 不存在也不报错

# 集合运算
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a | b)   # 并集: {1, 2, 3, 4, 5, 6}
print(a & b)   # 交集: {3, 4}
print(a - b)   # 差集: {1, 2}
print(a ^ b)   # 对称差集: {1, 2, 5, 6}

# 应用:去重
numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
unique = list(set(numbers))  # [1, 2, 3, 4]

典型案例:标签系统

# 文章标签
article1_tags = {"Python", "编程", "教程"}
article2_tags = {"Python", "Web", "Flask"}

# 共同标签
common = article1_tags & article2_tags
print(f"共同标签: {common}")

# 所有标签
all_tags = article1_tags | article2_tags
print(f"所有标签: {all_tags}")

# 独有标签
only_article1 = article1_tags - article2_tags
print(f"文章1独有: {only_article1}")

类型转换

# 数值转换
int("123")        # 123
float("3.14")     # 3.14
str(123)          # "123"

# 序列转换
list("hello")     # ['h', 'e', 'l', 'l', 'o']
tuple([1, 2, 3])  # (1, 2, 3)
set([1, 2, 2, 3]) # {1, 2, 3}

# 字典转换
dict([("a", 1), ("b", 2)])  # {'a': 1, 'b': 2}
list({"a": 1, "b": 2})      # ['a', 'b'](只有键)

练习

练习1:单词统计

text = "Python is great and Python is easy to learn Python"
words = text.lower().split()
word_count = {}
for word in words:
    word_count[word] = word_count.get(word, 0) + 1
print(word_count)

练习2:列表去重保持顺序

def unique_ordered(lst):
    seen = set()
    result = []
    for item in lst:
        if item not in seen:
            seen.add(item)
            result.append(item)
    return result

numbers = [3, 1, 2, 3, 2, 1, 4]
print(unique_ordered(numbers))  # [3, 1, 2, 4]

小结

类型是否可变是否有序是否可重复使用场景
str不可变有序可重复文本处理
list可变有序可重复通用集合
tuple不可变有序可重复固定数据
dict可变有序*键不可重复键值映射
set可变无序不可重复去重/集合运算

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

Prev
Python基础语法 - 缩进、变量、注释、输入输出 | HiHuo
Next
Python流程控制 - if条件判断、for/while循环 | HiHuo