Python教程:深入了解 Python 中 Dict、List、Tuple、Set 的高级用法

一.使用方法介绍


Python 中的 Dict(字典)、List(列表)、Tuple(元组)和 Set(集合)是常用的数据结构,它们各自有着不同的特性和用途。在本文中,我们将深入了解这些数据结构的高级用法,并提供详细的说明和代码示例。

1. 字典(Dict)

字典是一种无序的、可变的、键值对(key-value)集合,其中的键必须是唯一的。字典提供了高效的键值对查找和修改功能。

高级用法:

  • 字典推导式
  • 使用 collections.defaultdict
  • 使用 collections.Counter
# 字典推导式
squares = {x: x*x for x in range(1, 6)}
print(squares)

# 使用 collections.defaultdict
from collections import defaultdict
d = defaultdict(list)
d['group1'].append('value1')
print(d)

# 使用 collections.Counter
from collections import Counter
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
word_counts = Counter(words)
print(word_counts)

2. 列表(List)

列表是一种有序的、可变的序列,其中的元素可以是任意类型。列表提供了丰富的操作方法,如添加、删除、切片等。

高级用法:

  • 列表推导式
  • 使用 enumerate 获取索引和值
  • 使用 zip 合并列表
# 列表推导式
evens = [x for x in range(10) if x % 2 == 0]
print(evens)

# 使用 enumerate 获取索引和值
fruits = ['apple', 'banana', 'orange']
for index, value in enumerate(fruits):
    print(index, value)

# 使用 zip 合并列表
names = ['Alice', 'Bob', 'Charlie']
ages = [30, 25, 35]
for name, age in zip(names, ages):
    print(name, age)

3. 元组(Tuple)

元组是一种有序的、不可变的序列,类似于列表但是不可修改。元组通常用于存储不可变的数据集合。

高级用法:

  • 解构赋值
  • 使用 * 操作符解包
# 解构赋值
point = (3, 4)
x, y = point
print(x, y)

# 使用 * 操作符解包
numbers = (1, 2, 3, 4, 5)
first, *rest, last = numbers
print(first, last)

4. 集合(Set)

集合是一种无序的、不重复的元素集合,类似于数学中的集合概念。集合提供了高效的成员检查和集合操作。

高级用法:

  • 集合操作:并集、交集、差集、对称差集
  • 集合推导式
# 集合操作
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print("并集:", set1 | set2)
print("交集:", set1 & set2)
print("差集:", set1 - set2)
print("对称差集:", set1 ^ set2)

# 集合推导式
squares_set = {x*x for x in range(1, 6)}
print(squares_set)

二.Python 中 Dict、List、Tuple、Set 之间的相互转换


1. Dict(字典)转换为其他数据结构

1.1. Dict 转换为 List:

my_dict = {'a': 1, 'b': 2, 'c': 3}
dict_to_list = list(my_dict.items())
print(dict_to_list)

 1.2. Dict 转换为 Tuple:

my_dict = {'a': 1, 'b': 2, 'c': 3}
dict_to_tuple = tuple(my_dict.items())
print(dict_to_tuple)

1.3. Dict 转换为 Set:

my_dict = {'a': 1, 'b': 2, 'c': 3}
dict_to_set = set(my_dict.items())
print(dict_to_set)

2. List(列表)转换为其他数据结构

2.1. List 转换为 Dict:

my_list = [('a', 1), ('b', 2), ('c', 3)]
list_to_dict = dict(my_list)
print(list_to_dict)

2.2. List 转换为 Tuple:

my_list = [1, 2, 3]
list_to_tuple = tuple(my_list)
print(list_to_tuple)

2.3. List 转换为 Set:

my_list = [1, 2, 2, 3, 3, 4]
list_to_set = set(my_list)
print(list_to_set)

3. Tuple(元组)转换为其他数据结构

3.1. Tuple 转换为 Dict:

my_tuple = (('a', 1), ('b', 2), ('c', 3))
tuple_to_dict = dict(my_tuple)
print(tuple_to_dict)

3.2. Tuple 转换为 List:

my_tuple = (1, 2, 3)
tuple_to_list = list(my_tuple)
print(tuple_to_list)

3.3. Tuple 转换为 Set:

my_tuple = (1, 2, 2, 3, 3, 4)
tuple_to_set = set(my_tuple)
print(tuple_to_set)

4. Set(集合)转换为其他数据结构

4.1. Set 转换为 Dict:

注意:Set 中的元素必须是可哈希的,因此只能转换包含元组的集合。

my_set = {('a', 1), ('b', 2), ('c', 3)}
set_to_dict = dict(my_set)
print(set_to_dict)

4.2. Set 转换为 List 或 Tuple:

由于 Set 是无序的,转换为 List 或 Tuple 时顺序不确定,可以通过排序使结果有序。

my_set = {1, 2, 3}
set_to_list = sorted(list(my_set))
set_to_tuple = tuple(sorted(my_set))
print(set_to_list)
print(set_to_tuple)

三.实战应用


下面的示例代码,这是一个简单的学生管理系统,用于记录学生的信息,并实现一些功能,如添加学生、删除学生、按姓名查找学生等。这个示例会展示如何使用 Python 的 Dict、List、Tuple、Set 以及它们之间的相互转换。

class StudentManagementSystem:
    def __init__(self):
        self.students = []  # 学生列表,每个学生以字典形式存储
        self.student_set = set()  # 学生集合,用于快速查找学生是否存在

    def add_student(self, name, age, grade):
        student = {'name': name, 'age': age, 'grade': grade}
        self.students.append(student)
        self.student_set.add((name, age))  # 使用元组作为集合元素,保证唯一性

    def remove_student(self, name):
        for student in self.students:
            if student['name'] == name:
                self.students.remove(student)
                self.student_set.remove((student['name'], student['age']))
                return True
        return False

    def find_student_by_name(self, name):
        for student in self.students:
            if student['name'] == name:
                return student
        return None

    def display_all_students(self):
        for student in self.students:
            print(student)

    def get_students_set(self):
        return self.student_set

# 示例用法
sms = StudentManagementSystem()

# 添加学生
sms.add_student('Alice', 20, 'A')
sms.add_student('Bob', 21, 'B')
sms.add_student('Charlie', 22, 'C')

# 显示所有学生信息
print("所有学生信息:")
sms.display_all_students()

# 按姓名查找学生
print("\n按姓名查找学生:")
print(sms.find_student_by_name('Bob'))

# 删除学生
sms.remove_student('Bob')
print("\n删除学生后的所有学生信息:")
sms.display_all_students()

# 将学生集合转换为列表
student_set_as_list = sorted(list(sms.get_students_set()))
print("\n将学生集合转换为列表并排序:")
print(student_set_as_list)

相关推荐

  1. Pythonpythonisinstance

    2024-04-26 19:26:03       33 阅读
  2. PythonPython@wraps

    2024-04-26 19:26:03       34 阅读
  3. 案例学Python:filter()函数高级

    2024-04-26 19:26:03       50 阅读
  4. Python常见

    2024-04-26 19:26:03       65 阅读
  5. pythonprint函数

    2024-04-26 19:26:03       54 阅读
  6. pythonyield

    2024-04-26 19:26:03       62 阅读
  7. pythonsplit函数

    2024-04-26 19:26:03       45 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-26 19:26:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-26 19:26:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-26 19:26:03       82 阅读
  4. Python语言-面向对象

    2024-04-26 19:26:03       91 阅读

热门阅读

  1. make命令

    2024-04-26 19:26:03       35 阅读
  2. 大华相机C#学习之IStream类

    2024-04-26 19:26:03       28 阅读
  3. mybatis - 取值符号:# 和 $的区别

    2024-04-26 19:26:03       39 阅读
  4. 【动态规划】Leetcode 322. 零钱兑换【中等】

    2024-04-26 19:26:03       25 阅读
  5. 代谢网络模型学习笔记(序章)

    2024-04-26 19:26:03       33 阅读
  6. 设计模式之单例模式

    2024-04-26 19:26:03       31 阅读
  7. System.Exception有哪些类型分别什么意思

    2024-04-26 19:26:03       37 阅读