python 列表详解
Python 中的列表(list)是一个非常重要和常用的数据结构。关于 Python 列表的详细讲解,需要掌握如下知识点:
1. 定义与创建
- 列表是一个有序的元素集合,每个元素都有一个对应的索引。
- 列表的元素可以是任何数据类型,包括另一个列表。
- 列表用方括号
[]创建。
my_list = [1, 2, 3, 'apple', 'banana']
nested_list = [1, 2, [3, 4, 5], 'fruit']
2. 索引
- 列表的索引从 0 开始。
- 负数索引从列表的末尾开始。
fruits = ['apple', 'banana', 'cherry']
print(fruits[0]) # 输出:apple
print(fruits[-1]) # 输出:cherry
3. 切片
使用 : 可以从列表中提取多个元素(即切片)。
numbers = [0, 1, 2, 3, 4, 5, 6]
print(numbers[1:4]) # 输出:[1, 2, 3]
print(numbers[:3]) # 输出:[0, 1, 2]
print(numbers[4:]) # 输出:[4, 5, 6]
4. 修改列表
列表是可变的,这意味着你可以修改、添加或删除其内容。
fruits = ['apple', 'banana', 'cherry']
fruits[1] = 'blueberry'
print(fruits) # 输出:['apple', 'blueberry', 'cherry']
5. 添加元素
append(): 在列表末尾添加元素。insert(): 在指定索引位置插入元素。extend(): 通过另一个列表(或任何迭代)来扩展列表。
fruits = ['apple', 'banana', 'cherry']
fruits.append('date')
fruits.insert(1, 'avocado')
fruits.extend(['fig', 'grape'])
6. 删除元素
remove(): 删除指定的元素。pop(): 删除指定索引的元素(默认为最后一个元素)。del: 删除指定索引或切片的元素。clear(): 清空列表。
fruits = ['apple', 'banana', 'cherry']
fruits.remove('banana')
fruit_popped = fruits.pop()
del fruits[0]
fruits.clear()
7.列表长度
fruits = ['apple', 'banana', 'cherry', 'date']
length = len(fruits)
print(length) # 输出:4
8. 列表排序
numbers = [3, 1, 4, 2]
numbers.sort()
print(numbers) # 输出:[1, 2, 3, 4]
对字符串列表进行排序:
fruits.sort()
print(fruits) # 输出:['apple', 'banana', 'cherry', 'date']
9.反转列表
fruits.reverse()
print(fruits) # 输出:['date', 'cherry', 'banana', 'apple']
10.元素在列表中出现的次数
numbers = [1, 2, 3, 2, 4, 2, 5]
count_2 = numbers.count(2)
print(count_2) # 输出:3
11.返回元素首次出现的索引
index_cherry = fruits.index('cherry')
print(index_cherry) # 输出:1
注意:如果元素不在列表中,index() 会抛出一个异常。你可以为 index() 提供一个起始和结束的索引来限制搜索范围。
numbers = [1, 2, 3, 2, 4, 2, 5]
index_2_second_occurrence = numbers.index(2, 2)
print(index_2_second_occurrence) # 输出:3
上述例子中,numbers.index(2, 2) 会从索引为 2 的位置开始搜索数字 2 的首次出现,并返回它的索引。
12. 列表推导式
列表推导式提供了从旧列表创建新列表的简洁方式。
squares = [x**2 for x in range(10)]
13. 列表维度
在 Python 中,列表可以有任何数量的维度。维度通常用于描述数据的形状或结构。例如,在数据科学或机器学习中,通常使用多维数组来表示数据,但在 Python 的基本列表中,我们可以通过嵌套列表来模拟多维结构。
以下是关于列表维度的详细讲解:
13.1. 一维列表(1D)
一维列表就像一个普通的列表,它包含一系列的元素。
one_dim_list = [1, 2, 3, 4, 5]
13.2. 二维列表(2D)
二维列表是列表的列表,可以将其视为一个矩阵或表格。
two_dim_list = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
13.3. 三维列表(3D)
三维列表可以被视为“列表的列表的列表”。可以将其想象为多个 2D 列表或矩阵的堆叠。
three_dim_list = [
[
[1, 2],
[3, 4]
],
[
[5, 6],
[7, 8]
]
]
13.4. 更高维度
可以继续嵌套列表以创建更高维度的结构,但请注意,随着维度的增加,数据结构会变得更加复杂,操作和管理这些数据也会更加困难。
13.5. 访问多维列表的元素
使用多个索引可以访问多维列表中的元素。
# 获取二维列表中的元素
print(two_dim_list[0][2]) # 输出:3
# 获取三维列表中的元素
print(three_dim_list[1][0][1]) # 输出:6
本文详细介绍了Python列表的各种操作,包括定义与创建、索引、切片、修改、添加、删除、长度、排序、反转、元素计数、列表推导式以及不同维度列表的使用和元素访问。


985

被折叠的 条评论
为什么被折叠?



