python - 列表方法

在 Python 中,列表(List) 是最常用的组合数据类型之一,它支持多种方法用于增删改查、排序、反转等操作。以下是列表的 常用方法 及其示例:


1. 添加元素

(1) append(x)

  • 作用 :在列表 末尾 添加一个元素 x

  • 示例

    python 复制代码
    fruits = ["apple", "banana"]
    fruits.append("orange")
    print(fruits)  # 输出: ['apple', 'banana', 'orange']

(2) insert(i, x)

  • 作用 :在索引 i 处插入元素 x(原位置及之后的元素后移)。

  • 示例

    python 复制代码
    fruits = ["apple", "banana"]
    fruits.insert(1, "grape")
    print(fruits)  # 输出: ['apple', 'grape', 'banana']

(3) extend(iterable)

  • 作用 :将可迭代对象(如列表、元组、字符串等)的所有元素 追加 到列表末尾。

  • 示例

    python 复制代码
    nums = [1, 2, 3]
    nums.extend([4, 5])
    print(nums)  # 输出: [1, 2, 3, 4, 5]
     
    # 等价于 nums += [6, 7]
    nums += [6, 7]
    print(nums)  # 输出: [1, 2, 3, 4, 5, 6, 7]

2. 删除元素

(1) pop(i=-1)

  • 作用 :删除并返回索引 i 处的元素(默认删除最后一个元素)。

  • 示例

    python 复制代码
    fruits = ["apple", "banana", "cherry"]
    removed = fruits.pop(1)  # 删除索引 1 的元素
    print(removed)  # 输出: 'banana'
    print(fruits)   # 输出: ['apple', 'cherry']

(2) remove(x)

  • 作用 :删除列表中 第一个 值为 x 的元素(若不存在则报错 ValueError)。

  • 示例

    python 复制代码
    fruits = ["apple", "banana", "apple"]
    fruits.remove("apple")  # 删除第一个 "apple"
    print(fruits)  # 输出: ['banana', 'apple']

(3) clear()

  • 作用:清空列表(删除所有元素)。

  • 示例

    python 复制代码
    nums = [1, 2, 3]
    nums.clear()
    print(nums)  # 输出: []

(4) del 语句

  • 作用:通过索引或切片删除元素(支持删除多个元素)。

  • 示例

    python 复制代码
    nums = [0, 1, 2, 3, 4]
    del nums[0]      # 删除索引 0 的元素
    print(nums)      # 输出: [1, 2, 3, 4]
     
    del nums[1:3]    # 删除索引 1 到 2 的元素(左闭右开)
    print(nums)      # 输出: [1, 4]

3. 修改元素

(1) 直接通过索引修改

  • 示例

    python 复制代码
    nums = [1, 2, 3]
    nums[1] = 99
    print(nums)  # 输出: [1, 99, 3]

(2) 通过切片修改

  • 示例

    python 复制代码
    nums = [1, 2, 3, 4, 5]
    nums[1:4] = [20, 30, 40]  # 替换索引 1 到 3 的元素
    print(nums)  # 输出: [1, 20, 30, 40, 5]

4. 查找元素

(1) index(x, start=0, end=len(list))

  • 作用 :返回第一个值为 x 的元素的索引(若不存在则报错 ValueError)。

  • 示例

    python 复制代码
    fruits = ["apple", "banana", "cherry"]
    idx = fruits.index("banana")
    print(idx)  # 输出: 1

(2) count(x)

  • 作用 :返回值为 x 的元素在列表中出现的次数。

  • 示例

    python 复制代码
    nums = [1, 2, 2, 3, 2]
    cnt = nums.count(2)
    print(cnt)  # 输出: 3

(3) innot in

  • 作用 :检查元素是否在列表中(返回 TrueFalse)。

  • 示例

    python 复制代码
    fruits = ["apple", "banana"]
    print("apple" in fruits)   # 输出: True
    print("orange" not in fruits)  # 输出: True

5. 排序与反转

(1) sort(key=None, reverse=False)

  • 作用 :对列表 原地排序(默认升序)。

  • 参数

    • key:指定排序规则(如按字符串长度、字典的某个键等)。
    • reverse=True:降序排序。
  • 示例

    python 复制代码
    nums = [3, 1, 4, 1, 5, 9, 2]
    nums.sort()  # 升序排序
    print(nums)  # 输出: [1, 1, 2, 3, 4, 5, 9]
     
    nums.sort(reverse=True)  # 降序排序
    print(nums)  # 输出: [9, 5, 4, 3, 2, 1, 1]
     
    # 按字符串长度排序
    words = ["apple", "banana", "cherry", "date"]
    words.sort(key=lambda x: len(x))
    print(words)  # 输出: ['date', 'apple', 'banana', 'cherry']

(2) sorted(iterable, key=None, reverse=False)

  • 作用:返回一个新的排序后的列表(不修改原列表)。

  • 示例

    python 复制代码
    nums = [3, 1, 4, 1, 5]
    new_nums = sorted(nums)
    print(new_nums)  # 输出: [1, 1, 3, 4, 5]
    print(nums)      # 输出: [3, 1, 4, 1, 5](原列表未改变)

(3) reverse()

  • 作用 :反转列表 原地(不返回新列表)。

  • 示例

    scss 复制代码
    python
    nums = [1, 2, 3]
    nums.reverse()
    print(nums)  # 输出: [3, 2, 1]

(4) reversed(list)

  • 作用 :返回一个反转的迭代器(需用 list() 转换为列表)。

  • 示例

    python 复制代码
    nums = [1, 2, 3]
    new_nums = list(reversed(nums))
    print(new_nums)  # 输出: [3, 2, 1]

6. 复制列表

(1) 浅拷贝(Shallow Copy)

  • 方法

    • list.copy()
    • list[:]
    • list(original_list)
  • 示例

    python 复制代码
    original = [1, [2, 3], 4]
    copy1 = original.copy()
    copy2 = original[:]
    copy3 = list(original)
     
    # 修改嵌套列表会影响原列表(浅拷贝的局限性)
    copy1[1][0] = 99
    print(original)  # 输出: [1, [99, 3], 4]

(2) 深拷贝(Deep Copy)

  • 方法 :使用 copy.deepcopy()(需导入 copy 模块)。

  • 示例

    python 复制代码
    import copy
    original = [1, [2, 3], 4]
    deep_copy = copy.deepcopy(original)
     
    # 修改嵌套列表不会影响原列表
    deep_copy[1][0] = 99
    print(original)  # 输出: [1, [2, 3], 4]

7. 其他常用操作

(1) len(list)

  • 作用:返回列表的长度(元素个数)。

  • 示例

    python 复制代码
    nums = [1, 2, 3]
    print(len(nums))  # 输出: 3

(2) sum(list)

  • 作用:返回列表中所有数值元素的和(仅适用于数字列表)。

  • 示例

    python 复制代码
    nums = [1, 2, 3, 4]
    print(sum(nums))  # 输出: 10

(3) join(list)(仅适用于字符串列表)

  • 作用:将字符串列表拼接成一个字符串(需列表元素均为字符串)。

  • 示例

    python 复制代码
    words = ["Hello", "World", "Python"]
    sentence = " ".join(words)
    print(sentence)  # 输出: "Hello World Python"

总结:列表方法速查表

方法 作用 是否修改原列表
append(x) 末尾添加元素
insert(i, x) 指定位置插入元素
extend(iterable) 追加多个元素
pop(i) 删除并返回元素
remove(x) 删除第一个值为 x 的元素
clear() 清空列表
sort(key, reverse) 排序
reverse() 反转列表
copy() 浅拷贝列表 ❌(返回新列表)
index(x) 返回元素索引
count(x) 统计元素出现次数
len(list) 返回列表长度
sorted(list) 返回排序后的新列表
reversed(list) 返回反转的迭代器

练习题

  1. 创建一个列表 [1, 2, 3, 4, 5],并删除最后一个元素。
  2. 将列表 ["a", "b", "c"] 反转并打印。
  3. 统计列表 [1, 2, 2, 3, 2] 中数字 2 出现的次数。
  4. 对列表 ["banana", "apple", "cherry"] 按字母顺序排序。

答案

python 复制代码
# 1. 删除最后一个元素
nums = [1, 2, 3, 4, 5]
nums.pop()
print(nums)  # 输出: [1, 2, 3, 4]
 
# 2. 反转列表
letters = ["a", "b", "c"]
letters.reverse()
print(letters)  # 输出: ['c', 'b', 'a']
 
# 3. 统计数字 2 出现的次数
nums = [1, 2, 2, 3, 2]
print(nums.count(2))  # 输出: 3
 
# 4. 按字母顺序排序
fruits = ["banana", "apple", "cherry"]
fruits.sort()
print(fruits)  # 输出: ['apple', 'banana', 'cherry']
相关推荐
CodeCraft Studio5 小时前
PDF处理控件Aspose.PDF教程:使用 Python 将 PDF 转换为 Base64
开发语言·python·pdf·base64·aspose·aspose.pdf
困鲲鲲6 小时前
Python中内置装饰器
python
摩羯座-185690305947 小时前
Python数据可视化基础:使用Matplotlib绘制图表
大数据·python·信息可视化·matplotlib
爱隐身的官人7 小时前
cfshow-web入门-php特性
python·php·ctf
gb42152878 小时前
java中将租户ID包装为JSQLParser的StringValue表达式对象,JSQLParser指的是?
java·开发语言·python
THMAIL8 小时前
量化股票从贫穷到财务自由之路 - 零基础搭建Python量化环境:Anaconda、Jupyter实战指南
linux·人工智能·python·深度学习·机器学习·金融
~-~%%8 小时前
从PyTorch到ONNX:模型部署性能提升
人工智能·pytorch·python
蒋星熠8 小时前
Flutter跨平台工程实践与原理透视:从渲染引擎到高质产物
开发语言·python·算法·flutter·设计模式·性能优化·硬件工程
爬虫程序猿9 小时前
《京东商品详情爬取实战指南》
爬虫·python
胡耀超9 小时前
4、Python面向对象编程与模块化设计
开发语言·python·ai·大模型·conda·anaconda