目 录CONTENT

文章目录

Python:List、Set、Tuple、Dict

Administrator
2025-09-26 / 0 评论 / 0 点赞 / 0 阅读 / 0 字

 

字数 4227,阅读大约需 22 分钟

Python:List、Set、Tuple、Dict

4种常见的类型

  • 列表 (List): 有序、可变、异构的动态数组,可存储重复元素。

  • 元组 (Tuple): 有序但不可变,一旦创建就不能修改,可存储重复元素。

  • 集合 (Set): 无序、可变,只存储不重复的唯一元素,支持集合运算

  • 字典 (Dictionary): 通过唯一的键来高效存储和检索值的有序(Python 3.7+)可变集合。

Lists: A list is just like dynamic sized arrays, declared in other languages (vector in C++ and ArrayList in Java). Lists need not be homogeneous always which makes it the most powerful tool in Python.

Tuple: A Tuple is a collection of Python objects separated by commas. In some ways, a tuple is similar to a list in terms of indexing, nested objects, and repetition but a tuple is immutable, unlike lists that are mutable.

Set: A Set is an unordered collection data type that is iterable, mutable, and has no duplicate elements. Python’s set class represents the mathematical notion of a set.

Dictionary: In python, Dictionary is an ordered (since Py 3.7) [unordered (Py 3.6 & prior)] collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized.

Lists: A list is just like dynamic sized arrays, declared in other languages (vector in C++ and ArrayList in Java). Lists need not be homogeneous always which makes it the most powerful tool in Python.

Tuple: A Tuple is a collection of Python objects separated by commas. In some ways, a tuple is similar to a list in terms of indexing, nested objects, and repetition but a tuple is immutable, unlike lists that are mutable.

Set: A Set is an unordered collection data type that is iterable, mutable, and has no duplicate elements. Python’s set class represents the mathematical notion of a set.

Dictionary: In python, Dictionary is an ordered (since Py 3.7) [unordered (Py 3.6 & prior)] collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized.
好的,根据您提供的描述,以下是Python中这四种数据结构对应的类型和特点:


1. 列表 (List)

  • 对应类型: 动态数组 (Dynamic Sized Array),类似于C++的 vector 或 Java 的 ArrayList

  • 特点:

    • 有序 (Ordered): 元素有固定的排列顺序,可以通过索引访问。

    • 可变 (Mutable): 创建后可以修改(添加、删除、改变)其内容。

    • 元素可重复: 允许包含相同的元素。

    • 异构 (Heterogeneous): 可以存储不同数据类型的元素。

    • 动态大小: 可以随时调整大小,增加或减少元素。

    • 强大工具: 由于其灵活性,是Python中最常用的数据结构之一。


2. 元组 (Tuple)

  • 对应类型: 不可变序列 (Immutable Sequence)。

  • 特点:

    • 有序 (Ordered): 元素有固定的排列顺序,可以通过索引访问。

    • 不可变 (Immutable): 一旦创建,其内容(元素)就不能被修改、添加或删除。

    • 元素可重复: 允许包含相同的元素。

    • 异构 (Heterogeneous): 可以存储不同数据类型的元素。

    • 轻量高效: 由于其不可变性,通常比列表占用更少的内存,并且在某些操作上速度更快。

    • 安全性: 适合存储不应被修改的数据(如坐标、日期等)。


3. 集合 (Set)

  • 对应类型: 数学集合 (Mathematical Set)。

  • 特点:

    • 无序 (Unordered): 元素没有固定的排列顺序,不能通过索引访问。

    • 可变 (Mutable): 创建后可以修改(添加、删除)其内容。

    • 元素唯一: 不允许包含重复的元素,重复的元素会自动被移除。

    • 可迭代 (Iterable): 可以遍历其所有元素。

    • 主要用途: 常用于成员测试、删除序列中的重复元素以及执行数学集合运算(如并集、交集、差集等)。


4. 字典 (Dictionary)

  • 对应类型: 映射 (Map) 或哈希表 (Hash Table),键值对存储。

  • 特点:

    • 键值对 (Key-Value Pairs): 以键(key)和值(value)的形式存储数据,每个键都映射到一个值。

    • 键唯一: 每个键必须是唯一的,且不可变。值可以重复。

    • 有序 (Ordered): 自Python 3.7 版本起,字典保持插入时的顺序。在3.6及以前版本是无序的。

    • 可变 (Mutable): 创建后可以修改(添加、删除、改变)键值对。

    • 通过键快速查找: 提供高效的查找、添加和删除操作。

    • 异构: 键和值都可以是不同数据类型的。

代码演示

代码

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Python数据结构测试文件
包含List、Tuple、Set、Dictionary的详细说明和使用示例
"""

class TestDataStructures:
    """Python数据结构测试类"""

    def test_list_operations(self):
        """测试列表(List)操作"""
        print("=" * 60)
        print("列表(List)详解")
        print("=" * 60)

        """
        列表(List)详解:
        1. 基本概念:列表是Python中最常用的数据结构,类似于其他语言的数组
        2. 特性:有序、可变、允许重复元素、支持不同数据类型
        3. 创建方式:使用方括号[]或list()函数
        4. 索引:支持正向索引(0开始)和反向索引(-1开始)
        """

        # 创建列表的多种方式
        empty_list = []  # 空列表
        numbers_list = [1, 2, 3, 4, 5]  # 数字列表
        mixed_list = [1, "hello", 3.14, True]  # 混合类型列表
        nested_list = [[1, 2], [3, 4], [5, 6]]  # 嵌套列表

        print("1. 列表创建示例:")
        print(f"   空列表: {empty_list}")
        print(f"   数字列表: {numbers_list}")
        print(f"   混合类型列表: {mixed_list}")
        print(f"   嵌套列表: {nested_list}")

        # 基本操作
        print("\n2. 基本操作:")
        numbers = [1, 2, 3, 4, 5]

        # 访问元素
        print(f"   第一个元素: {numbers[0]}")
        print(f"   最后一个元素: {numbers[-1]}")
        print(f"   切片操作[1:4]: {numbers[1:4]}")

        # 修改元素
        numbers[0] = 10
        print(f"   修改后: {numbers}")

        # 添加元素
        numbers.append(6)  # 末尾添加
        numbers.insert(2, 15)  # 指定位置插入
        print(f"   添加元素后: {numbers}")

        # 删除元素
        numbers.remove(15)  # 删除指定值
        del numbers[0]  # 删除指定索引
        popped = numbers.pop()  # 删除并返回最后一个元素
        print(f"   删除元素后: {numbers}")
        print(f"   弹出的元素: {popped}")

        # 列表方法
        print("\n3. 常用列表方法:")
        fruits = ["apple", "banana", "cherry", "apple", "banana"]

        print(f"   原始列表: {fruits}")
        print(f"   长度: {len(fruits)}")
        print(f"   计数'banana': {fruits.count('banana')}")
        print(f"   索引'apple': {fruits.index('apple')}")
        print(f"   排序: {sorted(fruits)}")
        print(f"   反转: {list(reversed(fruits))}")

        # 列表推导式
        print("\n4. 列表推导式:")
        squares = [x**2 for x in range(1, 6)]
        even_numbers = [x for x in range(1, 11) if x % 2 == 0]
        print(f"   1-5的平方: {squares}")
        print(f"   1-10的偶数: {even_numbers}")

        # 实际应用示例
        print("\n5. 实际应用示例:")
        # 学生成绩管理系统
        students = [
            {"name": "张三", "score": 85, "age": 18},
            {"name": "李四", "score": 92, "age": 19},
            {"name": "王五", "score": 78, "age": 17}
        ]

        # 按成绩排序
        sorted_students = sorted(students, key=lambda x: x["score"], reverse=True)
        print("   按成绩排序的学生:")
        for student in sorted_students:
            print(f"     {student['name']}: {student['score']}分")

        # 统计分析
        scores = [s["score"] for s in students]
        print(f"   平均成绩: {sum(scores)/len(scores):.1f}")
        print(f"   最高成绩: {max(scores)}")
        print(f"   最低成绩: {min(scores)}")

    def test_tuple_operations(self):
        """测试元组(Tuple)操作"""
        print("\n" + "=" * 60)
        print("元组(Tuple)详解")
        print("=" * 60)

        """
        元组(Tuple)详解:
        1. 基本概念:元组是不可变的序列类型,类似于只读列表
        2. 特性:有序、不可变、允许重复元素、支持不同数据类型
        3. 创建方式:使用圆括号()或tuple()函数
        4. 优势:比列表更快、更安全、可以用作字典键
        """

        # 创建元组的多种方式
        empty_tuple = ()  # 空元组
        single_tuple = (1,)  # 单元素元组(注意逗号)
        numbers_tuple = (1, 2, 3, 4, 5)  # 数字元组
        mixed_tuple = (1, "hello", 3.14, True)  # 混合类型元组
        nested_tuple = ((1, 2), (3, 4), (5, 6))  # 嵌套元组

        print("1. 元组创建示例:")
        print(f"   空元组: {empty_tuple}")
        print(f"   单元素元组: {single_tuple}")
        print(f"   数字元组: {numbers_tuple}")
        print(f"   混合类型元组: {mixed_tuple}")
        print(f"   嵌套元组: {nested_tuple}")

        # 基本操作
        print("\n2. 基本操作:")
        coordinates = (10, 20, 30)

        # 访问元素
        print(f"   第一个元素: {coordinates[0]}")
        print(f"   最后一个元素: {coordinates[-1]}")
        print(f"   切片操作[1:3]: {coordinates[1:3]}")

        # 解包操作
        x, y, z = coordinates
        print(f"   解包: x={x}, y={y}, z={z}")

        # 元组方法
        print("\n3. 常用元组方法:")
        fruits = ("apple", "banana", "cherry", "apple", "banana")

        print(f"   原始元组: {fruits}")
        print(f"   长度: {len(fruits)}")
        print(f"   计数'banana': {fruits.count('banana')}")
        print(f"   索引'apple': {fruits.index('apple')}")

        # 元组推导式(生成器表达式)
        print("\n4. 元组推导式:")
        squares_gen = tuple(x**2 for x in range(1, 6))
        even_gen = tuple(x for x in range(1, 11) if x % 2 == 0)
        print(f"   1-5的平方: {squares_gen}")
        print(f"   1-10的偶数: {even_gen}")

        # 实际应用示例
        print("\n5. 实际应用示例:")
        # 坐标点
        point1 = (3, 4)
        point2 = (6, 8)

        # 计算距离
        distance = ((point2[0] - point1[0])**2 + (point2[1] - point1[1])**2)**0.5
        print(f"   两点距离: {distance:.2f}")

        # 函数返回多个值
        def get_student_info():
            return ("张三", 18, "计算机科学", 85)

        name, age, major, score = get_student_info()
        print(f"   学生信息: {name}, {age}岁, {major}, {score}分")

        # 用作字典键
        location_dict = {
            (39.9042, 116.4074): "北京",
            (31.2304, 121.4737): "上海",
            (22.3193, 114.1694): "深圳"
        }
        print(f"   坐标字典: {location_dict}")

    def test_set_operations(self):
        """测试集合(Set)操作"""
        print("\n" + "=" * 60)
        print("集合(Set)详解")
        print("=" * 60)

        """
        集合(Set)详解:
        1. 基本概念:集合是无序的、不重复的元素集合
        2. 特性:无序、唯一性、可变、支持数学集合操作
        3. 创建方式:使用花括号{}或set()函数
        4. 优势:快速查找、去重、数学运算
        """

        # 创建集合的多种方式
        empty_set = set()  # 空集合(注意:{}创建的是字典)
        numbers_set = {1, 2, 3, 4, 5}  # 数字集合
        mixed_set = {1, "hello", 3.14, True}  # 混合类型集合
        duplicate_set = {1, 2, 2, 3, 3, 3}  # 自动去重

        print("1. 集合创建示例:")
        print(f"   空集合: {empty_set}")
        print(f"   数字集合: {numbers_set}")
        print(f"   混合类型集合: {mixed_set}")
        print(f"   自动去重: {duplicate_set}")

        # 基本操作
        print("\n2. 基本操作:")
        fruits = {"apple", "banana", "cherry"}

        # 添加元素
        fruits.add("orange")
        fruits.update(["grape", "mango"])  # 添加多个元素
        print(f"   添加元素后: {fruits}")

        # 删除元素
        fruits.remove("banana")  # 删除指定元素(不存在会报错)
        fruits.discard("watermelon")  # 删除指定元素(不存在不会报错)
        popped = fruits.pop()  # 删除并返回任意元素
        print(f"   删除元素后: {fruits}")
        print(f"   弹出的元素: {popped}")

        # 集合运算
        print("\n3. 集合数学运算:")
        set_a = {1, 2, 3, 4, 5}
        set_b = {4, 5, 6, 7, 8}

        print(f"   集合A: {set_a}")
        print(f"   集合B: {set_b}")
        print(f"   并集(A | B): {set_a | set_b}")
        print(f"   交集(A & B): {set_a & set_b}")
        print(f"   差集(A - B): {set_a - set_b}")
        print(f"   对称差集(A ^ B): {set_a ^ set_b}")
        print(f"   A是否为B的子集: {set_a.issubset(set_b)}")
        print(f"   A是否为B的超集: {set_a.issuperset(set_b)}")

        # 集合推导式
        print("\n4. 集合推导式:")
        squares_set = {x**2 for x in range(1, 6)}
        even_set = {x for x in range(1, 11) if x % 2 == 0}
        print(f"   1-5的平方集合: {squares_set}")
        print(f"   1-10的偶数集合: {even_set}")

        # 实际应用示例
        print("\n5. 实际应用示例:")
        # 去重统计
        numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
        unique_numbers = set(numbers)
        print(f"   原始列表: {numbers}")
        print(f"   去重后集合: {unique_numbers}")
        print(f"   唯一元素数量: {len(unique_numbers)}")

        # 查找共同元素
        list1 = ["apple", "banana", "cherry", "date"]
        list2 = ["banana", "date", "elderberry", "fig"]
        common = set(list1) & set(list2)
        only_in_list1 = set(list1) - set(list2)
        only_in_list2 = set(list2) - set(list1)
        print(f"   列表1: {list1}")
        print(f"   列表2: {list2}")
        print(f"   共同元素: {common}")
        print(f"   仅在列表1中: {only_in_list1}")
        print(f"   仅在列表2中: {only_in_list2}")

    def test_dict_operations(self):
        """测试字典(Dictionary)操作"""
        print("\n" + "=" * 60)
        print("字典(Dictionary)详解")
        print("=" * 60)

        """
        字典(Dictionary)详解:
        1. 基本概念:字典是键值对的集合,使用键来访问值
        2. 特性:无序(Python 3.7+有序)、键唯一、值可重复、可变
        3. 创建方式:使用花括号{}或dict()函数
        4. 优势:快速查找、灵活的数据结构
        """

        # 创建字典的多种方式
        empty_dict = {}  # 空字典
        person_dict = {"name": "张三", "age": 25, "city": "北京"}  # 基本字典
        nested_dict = {
            "student": {"name": "李四", "age": 20},
            "teacher": {"name": "王五", "age": 35}
        }  # 嵌套字典

        print("1. 字典创建示例:")
        print(f"   空字典: {empty_dict}")
        print(f"   人员信息字典: {person_dict}")
        print(f"   嵌套字典: {nested_dict}")

        # 基本操作
        print("\n2. 基本操作:")
        student = {"name": "张三", "age": 18, "score": 85}

        # 访问值
        print(f"   姓名: {student['name']}")
        print(f"   年龄: {student.get('age', '未知')}")
        print(f"   成绩: {student.get('grade', '无')}")  # 不存在时返回默认值

        # 修改和添加
        student["age"] = 19  # 修改现有键
        student["grade"] = "A"  # 添加新键值对
        print(f"   修改后: {student}")

        # 删除
        del student["score"]  # 删除指定键
        removed_value = student.pop("grade")  # 删除并返回指定键的值
        print(f"   删除后: {student}")
        print(f"   删除的值: {removed_value}")

        # 字典方法
        print("\n3. 常用字典方法:")
        print(f"   所有键: {list(student.keys())}")
        print(f"   所有值: {list(student.values())}")
        print(f"   所有键值对: {list(student.items())}")
        print(f"   字典长度: {len(student)}")
        print(f"   是否包含'name': {'name' in student}")
        print(f"   是否包含'gender': {'gender' in student}")

        # 字典推导式
        print("\n4. 字典推导式:")
        squares_dict = {x: x**2 for x in range(1, 6)}
        even_dict = {x: x*2 for x in range(1, 6) if x % 2 == 0}
        print(f"   1-5的平方字典: {squares_dict}")
        print(f"   1-5偶数的倍数字典: {even_dict}")

        # 实际应用示例
        print("\n5. 实际应用示例:")
        # 学生成绩管理系统
        students = {
            "张三": {"age": 18, "math": 85, "english": 92, "chinese": 88},
            "李四": {"age": 19, "math": 78, "english": 85, "chinese": 90},
            "王五": {"age": 17, "math": 95, "english": 88, "chinese": 92}
        }

        print("   学生成绩信息:")
        for name, info in students.items():
            total = info["math"] + info["english"] + info["chinese"]
            average = total / 3
            print(f"     {name}: 总分{total}, 平均分{average:.1f}")

        # 统计分析
        all_scores = []
        for student_info in students.values():
            all_scores.extend([student_info["math"], student_info["english"], student_info["chinese"]])

        print("   班级统计:")
        print(f"     总分: {sum(all_scores)}")
        print(f"     平均分: {sum(all_scores)/len(all_scores):.1f}")
        print(f"     最高分: {max(all_scores)}")
        print(f"     最低分: {min(all_scores)}")

        # 按成绩排序
        sorted_students = sorted(students.items(), key=lambda x: sum(x[1].values()) / 3, reverse=True)
        print("   按平均分排序:")
        for name, info in sorted_students:
            avg_score = sum(info.values()) / 3
            print(f"     {name}: {avg_score:.1f}分")

    def run_all_tests(self):
        """运行所有数据结构测试"""
        print("Python数据结构完整测试")
        print("测试时间:", __import__('datetime').datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        print()

        self.test_list_operations()
        self.test_tuple_operations()
        self.test_set_operations()
        self.test_dict_operations()

        print("\n" + "=" * 60)
        print("所有测试完成!")
        print("=" * 60)


# 主程序入口
if __name__ == "__main__":
    tester = TestDataStructures()
    tester.run_all_tests()

执行


set_dict_list_tuple_test.py::TestDataStructures::test_list_operations PASSED [ 25%]============================================================
列表(List)详解
============================================================
1. 列表创建示例:
   空列表: []
   数字列表: [1, 2, 3, 4, 5]
   混合类型列表: [1, 'hello', 3.14, True]
   嵌套列表: [[1, 2], [3, 4], [5, 6]]

2. 基本操作:
   第一个元素: 1
   最后一个元素: 5
   切片操作[1:4]: [2, 3, 4]
   修改后: [10, 2, 3, 4, 5]
   添加元素后: [10, 2, 15, 3, 4, 5, 6]
   删除元素后: [2, 3, 4, 5]
   弹出的元素: 6

3. 常用列表方法:
   原始列表: ['apple', 'banana', 'cherry', 'apple', 'banana']
   长度: 5
   计数'banana': 2
   索引'apple': 0
   排序: ['apple', 'apple', 'banana', 'banana', 'cherry']
   反转: ['banana', 'apple', 'cherry', 'banana', 'apple']

4. 列表推导式:
   1-5的平方: [1, 4, 9, 16, 25]
   1-10的偶数: [2, 4, 6, 8, 10]

5. 实际应用示例:
   按成绩排序的学生:
     李四: 92分
     张三: 85分
     王五: 78分
   平均成绩: 85.0
   最高成绩: 92
   最低成绩: 78

set_dict_list_tuple_test.py::TestDataStructures::test_tuple_operations PASSED [ 50%]
============================================================
元组(Tuple)详解
============================================================
1. 元组创建示例:
   空元组: ()
   单元素元组: (1,)
   数字元组: (1, 2, 3, 4, 5)
   混合类型元组: (1, 'hello', 3.14, True)
   嵌套元组: ((1, 2), (3, 4), (5, 6))

2. 基本操作:
   第一个元素: 10
   最后一个元素: 30
   切片操作[1:3]: (20, 30)
   解包: x=10, y=20, z=30

3. 常用元组方法:
   原始元组: ('apple', 'banana', 'cherry', 'apple', 'banana')
   长度: 5
   计数'banana': 2
   索引'apple': 0

4. 元组推导式:
   1-5的平方: (1, 4, 9, 16, 25)
   1-10的偶数: (2, 4, 6, 8, 10)

5. 实际应用示例:
   两点距离: 5.00
   学生信息: 张三, 18岁, 计算机科学, 85分
   坐标字典: {(39.9042, 116.4074): '北京', (31.2304, 121.4737): '上海', (22.3193, 114.1694): '深圳'}

set_dict_list_tuple_test.py::TestDataStructures::test_set_operations PASSED [ 75%]
============================================================
集合(Set)详解
============================================================
1. 集合创建示例:
   空集合: set()
   数字集合: {1, 2, 3, 4, 5}
   混合类型集合: {1, 3.14, 'hello'}
   自动去重: {1, 2, 3}

2. 基本操作:
   添加元素后: {'mango', 'grape', 'orange', 'cherry', 'banana', 'apple'}
   删除元素后: {'grape', 'orange', 'cherry', 'apple'}
   弹出的元素: mango

3. 集合数学运算:
   集合A: {1, 2, 3, 4, 5}
   集合B: {4, 5, 6, 7, 8}
   并集(A | B): {1, 2, 3, 4, 5, 6, 7, 8}
   交集(A & B): {4, 5}
   差集(A - B): {1, 2, 3}
   对称差集(A ^ B): {1, 2, 3, 6, 7, 8}
   A是否为B的子集: False
   A是否为B的超集: False

4. 集合推导式:
   1-5的平方集合: {1, 4, 9, 16, 25}
   1-10的偶数集合: {2, 4, 6, 8, 10}

5. 实际应用示例:
   原始列表: [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
   去重后集合: {1, 2, 3, 4}
   唯一元素数量: 4
   列表1: ['apple', 'banana', 'cherry', 'date']
   列表2: ['banana', 'date', 'elderberry', 'fig']
   共同元素: {'banana', 'date'}
   仅在列表1中: {'cherry', 'apple'}
   仅在列表2中: {'elderberry', 'fig'}

set_dict_list_tuple_test.py::TestDataStructures::test_dict_operations PASSED [100%]
============================================================
字典(Dictionary)详解
============================================================
1. 字典创建示例:
   空字典: {}
   人员信息字典: {'name': '张三', 'age': 25, 'city': '北京'}
   嵌套字典: {'student': {'name': '李四', 'age': 20}, 'teacher': {'name': '王五', 'age': 35}}

2. 基本操作:
   姓名: 张三
   年龄: 18
   成绩: 无
   修改后: {'name': '张三', 'age': 19, 'score': 85, 'grade': 'A'}
   删除后: {'name': '张三', 'age': 19}
   删除的值: A

3. 常用字典方法:
   所有键: ['name', 'age']
   所有值: ['张三', 19]
   所有键值对: [('name', '张三'), ('age', 19)]
   字典长度: 2
   是否包含'name': True
   是否包含'gender': False

4. 字典推导式:
   1-5的平方字典: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
   1-5偶数的倍数字典: {2: 4, 4: 8}

5. 实际应用示例:
   学生成绩信息:
     张三: 总分265, 平均分88.3
     李四: 总分253, 平均分84.3
     王五: 总分275, 平均分91.7
   班级统计:
     总分: 793
     平均分: 88.1
     最高分: 95
     最低分: 78
   按平均分排序:
     王五: 97.3分
     张三: 94.3分
     李四: 90.7分


============================== 4 passed in 0.03s ===============================

进程已结束,退出代码为 0

 

0
  1. 支付宝打赏

    qrcode alipay
  2. 微信打赏

    qrcode weixin

评论区