列表的基本概念
列表是Python中最常用的数据结构之一,用于存储多个元素的有序集合。列表是可变的,这意味着可以修改、添加和删除列表中的元素。
标题列表的创建和访问
# 创建列表
fruits = ['apple', 'banana', 'orange']
# 生成式创建列表 由1到9的数字构成的列表
print([x for x in range(1, 10)]) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# 通过索引访问列表元素
print(fruits[0]) # 输出: apple
# 使用切片访问列表的子集
print(fruits[1:3]) # 输出: ['banana', 'orange']
掌握列表的基本操作
使用方法和操作符来修改和操作列表
# 向列表末尾添加元素
fruits.append('grape')
print(fruits) # 输出: ['apple', 'banana', 'orange', 'grape']
# 在指定位置插入元素
fruits.insert(1, 'mango')
print(fruits) # 输出: ['apple', 'mango', 'banana', 'orange', 'grape']
# 修改列表中的元素
fruits[2] = 'kiwi'
print(fruits) # 输出: ['apple', 'mango', 'kiwi', 'orange', 'grape']
# 删除列表中的元素
del fruits[0]
print(fruits) # 输出: ['mango', 'kiwi', 'orange', 'grape']
# 列表的拼接
print(fruits + fruits) # 输出: ['mango', 'kiwi', 'orange', 'grape', 'mango', 'kiwi', 'orange', 'grape']
# 列表的重复
print(fruits * 2) # 输出: ['mango', 'kiwi', 'orange', 'grape', 'mango', 'kiwi', 'orange', 'grape']
# 列表的比较
print(fruits == fruits * 2) # 输出: False
理解列表的常用方法和函数
列表有许多内置方法和函数可用于操作和处理
# 列表排序
fruits.sort()
print(fruits) # 输出: ['grape', 'kiwi', 'mango', 'orange']
# 列表反转
fruits.reverse()
print(fruits) # 输出: ['orange', 'mango', 'kiwi', 'grape']
# 获取列表的长度
length = len(fruits)
print(length) # 输出: 4
# 计算列表中特定元素的数量
count = fruits.count('mango')
print(count) # 输出: 1
# 查找元素在列表中的索引
index = fruits.index('kiwi')
print(index) # 输出: 2
# 查找元素在列表中的索引
index = fruits.index('知识星球:小问号')
print(index) # 输出: ValueError: 知识星球:小问号 is not in list
练习和实践
通过编写代码来操作和处理列表,例如:
创建一个数字列表,找出其中的最大值和最小值。
创建一个字符串列表,对列表中的字符串进行拼接。