Skip to content

列表、元组、集合、字典的基本概念和常用操作方法

列表详解

列表本身支持很多方法,这里只介绍一些常用的。

方法参数描述
append(object)object: 要添加的元素在列表末尾添加一个元素
extend(iterable)iterable: 可迭代对象(列表、元组等)在列表末尾添加另一个可迭代对象的所有元素
insert(index, object)index: 插入位置的索引, object: 要插入的元素在指定索引位置插入一个元素
remove(object)object: 要移除的元素移除列表中第一个匹配的元素
pop([index])index: 要移除元素的索引位置(可选)移除并返回指定索引的元素,默认为最后一个元素
sort()[key=None, reverse=False]对列表进行原地排序,key指定排序函数,reverse指定是否倒序
reverse()反转列表中的元素顺序
clear()移除列表中的所元素
copy()返回列表的浅拷贝
index(object)object: 要查找的元素返回指定元素在列表中首次出现的索引位置
python
# 创建一个列表
fruits = ['apple', 'banana', 'orange']

# append 示例
fruits.append('grape')
print(fruits)  # ['apple', 'banana', 'orange', 'grape']

# extend 示例
more_fruits = ['mango', 'pear']
fruits.extend(more_fruits)
print(fruits)  # ['apple', 'banana', 'orange', 'grape', 'mango', 'pear']

# insert 示例
fruits.insert(1, 'kiwi')
print(fruits)  # ['apple', 'kiwi', 'banana', 'orange', 'grape', 'mango', 'pear']

# remove 示例
fruits.remove('banana')
print(fruits)  # ['apple', 'kiwi', 'orange', 'grape', 'mango', 'pear']

# pop 示例
last_fruit = fruits.pop()
print(last_fruit)  # pear
print(fruits)  # ['apple', 'kiwi', 'orange', 'grape', 'mango']

# sort 示例
fruits.sort()
print(fruits)  # ['apple', 'grape', 'kiwi', 'mango', 'orange']

# reverse 示例
fruits.reverse()
print(fruits)  # ['orange', 'mango', 'kiwi', 'grape', 'apple']

# index 示例
print(fruits.index('kiwi'))  # 2

# clear 示例
fruits_copy = fruits.copy()  # 创建副本以便演示
fruits_copy.clear()
print(fruits_copy)  # []

用列表实现队列

队列是一种先进先出(FIFO)的数据结构。

python
queue = []

# 入队
queue.append('task1')
queue.append('task2')

# 出队
print(queue.pop(0))  # task1

用列表实现堆栈

堆栈是一种后进先出(LIFO)的数据结构。

python
stack = []

# 入栈
stack.append('task1')
stack.append('task2')

# 出栈
print(stack.pop())  # task2

列表推导式

列表推导式是一种简洁的创建列表的方式。

python
squares = []
for x in range(10):
    squares.append(x**2)

squares = [x**2 for x in range(10)]

del 语句

del 语句可以删除变量、列表元素、切片,甚至是整个对象。

python
# 删除变量
x = 1
del x
# print(x)  # NameError: name 'x' is not defined

# 删除列表元素
nums = [1, 2, 3, 4, 5]
del nums[0]  # 删除第一个元素
print(nums)  # [2, 3, 4, 5]

# 删除切片
nums = [1, 2, 3, 4, 5]
del nums[1:3]  # 删除索引1到2的元素
print(nums)  # [1, 4, 5]

# 删除整个列表
nums = [1, 2, 3]
del nums
# print(nums)  # NameError: name 'nums' is not defined

tuple 元祖和序列

列表和字符串有共同点:都可以通过索引访问元素,都可以切片。这两种类型称为序列,元祖也是一种序列,但是元祖是不可变的。

元祖的声明使用小括号,元素之间用逗号分隔。也可以不使用小括号。当只有一个元素时使用括号不雅观,所以可以使用一个逗号。

python
t = 12345, 54321, 'hello!'
t1 = (12345, 54321, 'hello!')

t2 = 12345,

set 集合

由不重复的元素组成的一种无序容器,基本用法包括成员检测、消除重复元素。集合对象支持合集、交集、差集、对称差分等数学运算。

集合的创建使用 set() 函数或直接用大括号。空集合必须使用 set() 创建

python
# 创建集合
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket)  # {'orange', 'banana', 'pear', 'apple'}

集合同样支持推导式

python
squares = {x**2 for x in range(10)}
print(squares)  # {0, 1, 64, 4, 36, 9, 16, 49, 81, 25}

NOTE

逻辑运算符科普

运算符描述
&交集,且
|并集,或
-差集
^对称差分,两个集合中存在,但不同时存在
python
# 集合运算示例
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

# 交集
print(a & b)  # {3, 4}

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

# 差集
print(a - b)  # {1, 2}
print(b - a)  # {5, 6}

# 对称差分
print(a ^ b)  # {1, 2, 5, 6}

集合常用方法

方法参数描述
add(object)object: 要添加的元素添加一个元素到集合中
update(iterable)iterable: 可迭代对象(列表、元组等)添加多个元素到集合中
remove(object)object: 要移除的元素移除一个元素
discard(object)object: 要移除的元素移除一个元素,如果元素不存在,不报错
clear()移除集合中的所有元素
copy()返回集合的浅拷贝
python
# 创建一个集合
fruits = {'apple', 'banana', 'orange'}

# add 示例
fruits.add('grape')
print(fruits)  # {'apple', 'banana', 'orange', 'grape'}

# update 示例
more_fruits = {'mango', 'pear'}
fruits.update(more_fruits)
print(fruits)  # {'apple', 'banana', 'orange', 'grape', 'mango', 'pear'}

# remove 示例
fruits.remove('banana')
print(fruits)  # {'apple', 'orange', 'grape', 'mango', 'pear'}

# discard 示例
fruits.discard('kiwi')  # 不存在也不会报错
print(fruits)  # {'apple', 'orange', 'grape', 'mango', 'pear'}

# clear 示例
fruits.clear()
print(fruits)  # set()

# copy 示例
original = {'a', 'b', 'c'}
copied = original.copy()
print(copied)  # {'a', 'b', 'c'}

dict 字典

可以看做键值对的无序集合。key 必须是唯一的;检查某个字典中是否存在某个键,使用 in 关键字。创建字段的方��有三种。

  • 直接使用大括号
  • 使用 dict() 函数
  • 使用字典推导式
python
# 直接使用大括号
tel = {'jack': 4098, 'sape': 4139}

# 使用 dict() 序列方式创建
tel = dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])

# 使用 dict() 关键字方式创建
tel = dict(sape=4139, guido=4127, jack=4098)

# 使用字典推导式
tel = {x: x**2 for x in (2, 4, 6)}

字典的取值使用 [key] 来获取,如果键不存在,会报错。赋值使用 [key] = value 来赋值;赋值的 key 不存在时,会创建一个新的键值对。

python
d = {'a': 1, 'b': 2}
print(d['a'])  # 1

d['a'] = 3
print(d)  # {'a': 3, 'b': 2}

d['c'] = 3
print(d)  # {'a': 3, 'b': 2, 'c': 3}

字典常用方法

方法参数描述
clear()移除字典中的所有元素
copy()返回字典的浅拷贝
get(key[, default])key: 要查找的键, default: 默认值(可选)返回指定键的值,如果键不存在,返回默认值
items()返回字典的键值对视图
keys()返回字典的键视图
values()返回字典的值视图
python
# 创建一个字典
d = {'a': 1, 'b': 2, 'c': 3}

# clear 示例
d.clear()
print(d)  # {}

# copy 示例
d = {'a': 1, 'b': 2, 'c': 3}
d2 = d.copy()
print(d2)  # {'a': 1, 'b': 2, 'c': 3}

# get 示例
d = {'a': 1, 'b': 2, 'c': 3}
print(d.get('a'))  # 1
print(d.get('d', 0))  # 0 (键不存在,返回默认值)

# items 示例
d = {'a': 1, 'b': 2, 'c': 3}
print(list(d.items()))  # [('a', 1), ('b', 2), ('c', 3)]

# keys 示例
print(list(d.keys()))  # ['a', 'b', 'c']

# values 示例
print(list(d.values()))  # [1, 2, 3]

循环的技巧

当对字典进行循环时,可以使用 items() 方法来获取键值对。

python
d = {'a': 1, 'b': 2, 'c': 3}
for key, value in d.items():
    print(key, value)

当对序列进行循环时,可以使用 enumerate() 函数来获取索引和值。

python
for i, v in enumerate(['tic', 'tac', 'toe']):
    print(i, v)
# 0 tic
# 1 tac
# 2 toe

对两个或多个序列进行循环时,可以使用 zip() 函数来获取多个序列的值。循环的次数取决于最短的序列。

python
questions = ['name', 'quest', 'favorite color'] 
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
    print('What is your {0}?  It is {1}.'.format(q, a))
# What is your name?  It is lancelot.
# What is your quest?  It is the holy grail.
# What is your favorite color?  It is blue.

深入条件控制

Python 中的比较运算符和���辑运算符有以下几种:

运算符描述示例
==等于a == b
!=不等于a != b
>大于a > b
<小于a < b
>=大于等于a >= b
<=小于等于a <= b
and逻辑与a and b
or逻辑或a or b
not逻辑非not a
is身份运算符a is b
is not身份运算符a is not b
in成员运算符a in b
not in成员运算符a not in b

运算符优先级从高到低排列如下:

  1. () 括号
  2. ** 指数
  3. *, /, //, % 乘、除、整除、取余
  4. +, - 加、减
  5. in, not in, is, is not, <, <=, >, >=, !=, == 比较运算符
  6. not 逻辑非
  7. and 逻辑与
  8. or 逻辑或

类型转换

函数描述示例
int()将对象转换为整数int('123') -> 123
float()将对象转换为浮点数float('3.14') -> 3.14
str()将对象转换为字符串str(123) -> '123'
bool()将对象转换为布尔值bool(1) -> True
list()将可迭代对象转换为列表list('abc') -> ['a','b','c']
tuple()将可迭代对象转换为元组tuple([1,2,3]) -> (1,2,3)
set()将可迭代对���转换为集合set([1,1,2]) -> {1,2}

对字典使用 list(), tuple()set() 进行转换时,只会对字典的键进行浅拷贝。

练习题

基础练习

  1. 列表操作

    python
    # 创建一个列表 numbers,包含数字 1-5
    # 要求:
    # 1. 在末尾添加数字 6
    # 2. 在索引 1 的位置插入数字 10
    # 3. 删除最后一个元素
    # 4. 将列表反转
    # 请写出完整的代码
  2. 集合运算

    python
    # 有两个集合:
    set1 = {1, 2, 3, 4, 5}
    set2 = {4, 5, 6, 7, 8}
    # 请计算:
    # 1. 两个集合的交集
    # 2. 两个集合的并集
    # 3. set1 相对于 set2 的差集
    # 4. 两个集合的对称差集
  3. 字典操作

    python
    # 创建一个字典,存储以下学生的成绩:
    # Tom: 90, Jerry: 85, Alice: 95
    # 要求:
    # 1. 添加一个新学生 Bob: 88
    # 2. 修改 Tom 的成绩为 92
    # 3. 删除 Jerry 的成绩
    # 4. 打印所有学生的平均成绩

进阶练习

  1. 列表推导式

    python
    # 使用列表推导式完成以下任务:
    # 1. 生成 1-20 之间的偶数列表
    # 2. 生成一个列表,包含 1-10 的平方数
    # 3. 从字符串列表 ["hello", "world", "python"] 中
    #    生成一个新列表,只包含长度���于 5 的单词
  2. 字典处理

    python
    # 有如下字典:
    sales = {
        'apple': [5, 2, 7, 4],
        'banana': [3, 6, 9, 2],
        'orange': [6, 3, 4, 5]
    }
    # 要求:
    # 1. 计算每种水果的总销售量
    # 2. 找出销售量最高的水果
    # 3. 创建一个新字典,记录每种水果的平均销售量

挑战题

  1. 数据结构综合运用
    python
    # 实现一个简单的学生成绩管理系统,要求:
    # 1. 使用字典存储学生信息,包括姓名、年龄和各科成绩(语文、数学、英语)
    # 2. 实现添加学生信息的功能
    # 3. 实现删除学生信息的功能
    # 4. 实现查询学生平均成绩的功能
    # 5. 实现按照总分对学生进行排序的功能

参考答案

点击查看答案

基础练习答案

  1. 列表操作

    python
    numbers = [1, 2, 3, 4, 5]
    numbers.append(6)
    numbers.insert(1, 10)
    numbers.pop()
    numbers.reverse()
    print(numbers)  # [5, 4, 3, 10, 2, 1]
  2. 集合运算

    python
    set1 = {1, 2, 3, 4, 5}
    set2 = {4, 5, 6, 7, 8}
    
    intersection = set1 & set2
    union = set1 | set2
    difference = set1 - set2
    symmetric_difference = set1 ^ set2
    
    print(f"交集: {intersection}")  # {4, 5}
    print(f"并集: {union}")  # {1, 2, 3, 4, 5, 6, 7, 8}
    print(f"差集: {difference}")  # {1, 2, 3}
    print(f"对称差集: {symmetric_difference}")  # {1, 2, 3, 6, 7, 8}
  3. 字典操作

    python
    grades = {'Tom': 90, 'Jerry': 85, 'Alice': 95}
    
    # 添加新学生
    grades['Bob'] = 88
    
    # 修改 Tom 的成绩
    grades['Tom'] = 92
    
    # 删除 Jerry 的成绩
    del grades['Jerry']
    
    # 计算平均成绩
    average = sum(grades.values()) / len(grades)
    print(f"平均成绩: {average}")  # 91.67

进阶练习答案

  1. 列表推导式

    python
    # 1-20 之间的偶数
    even_numbers = [x for x in range(1, 21) if x % 2 == 0]
    
    # 1-10 的平方数
    squares = [x**2 for x in range(1, 11)]
    
    # 长度大于 5 的单词
    words = ["hello", "world", "python"]
    long_words = [word for word in words if len(word) > 5]
  2. 字典处理

    python
    sales = {
        'apple': [5, 2, 7, 4],
        'banana': [3, 6, 9, 2],
        'orange': [6, 3, 4, 5]
    }
    
    # 总销售量
    total_sales = {fruit: sum(amounts) for fruit, amounts in sales.items()}
    
    # 销售量最高的水果
    best_seller = max(total_sales.items(), key=lambda x: x[1])
    
    # 平均销售量
    avg_sales = {fruit: sum(amounts)/len(amounts) for fruit, amounts in sales.items()}
    
    print(f"总销售量: {total_sales}")
    print(f"销售冠军: {best_seller[0]}")
    print(f"平均销售量: {avg_sales}")

挑战题答案

  1. 数据结构综合运用
    python
    class StudentManager:
        def __init__(self):
            self.students = {}
    
        def add_student(self, name, age, chinese, math, english):
            self.students[name] = {
                'age': age,
                'scores': {
                    'chinese': chinese,
                    'math': math,
                    'english': english
                }
            }
    
        def remove_student(self, name):
            if name in self.students:
                del self.students[name]
                return True
            return False
    
        def get_average(self, name):
            if name in self.students:
                scores = self.students[name]['scores'].values()
                return sum(scores) / len(scores)
            return None
    
        def sort_by_total(self):
            def total_score(item):
                return sum(item[1]['scores'].values())
            
            return dict(sorted(
                self.students.items(),
                key=total_score,
                reverse=True
            ))
    
    # 使用示例
    manager = StudentManager()
    manager.add_student('Alice', 18, 90, 95, 88)
    manager.add_student('Bob', 19, 85, 90, 92)
    manager.add_student('Charlie', 18, 88, 88, 90)
    
    print(f"Alice's average: {manager.get_average('Alice')}")
    print("Sorted students:", manager.sort_by_total())

TIP

建议先独立完成练习,遇到困难时再参考答案。这样能够更好地掌握所学知识。