0
点赞
收藏
分享

微信扫一扫

列表常用的操作方法有哪些?

在Python中,列表(list)提供了丰富的内置方法来方便地操作元素。以下是列表最常用的操作方法,按功能分类说明:

一、添加元素

用于向列表中新增元素,常用方法有:

  1. append(x) 在列表末尾添加单个元素x(直接修改原列表,无返回值)。

fruits = ["apple", "banana"]
fruits.append("cherry")  # 在末尾添加
print(fruits)  # 输出: ["apple", "banana", "cherry"]

  1. insert(index, x) 在指定索引index处插入元素x(原索引及之后的元素后移)。

fruits = ["apple", "banana"]
fruits.insert(1, "orange")  # 在索引1处插入
print(fruits)  # 输出: ["apple", "orange", "banana"]

  1. extend(iterable)

fruits = ["apple", "banana"]
more_fruits = ["cherry", "grape"]
fruits.extend(more_fruits)  # 添加多个元素
print(fruits)  # 输出: ["apple", "banana", "cherry", "grape"]

二、删除元素

用于移除列表中的元素,常用方法/语句有:

  1. remove(x) 移除列表中第一个匹配元素x(若x不存在则报错)。

fruits = ["apple", "banana", "apple"]
fruits.remove("apple")  # 只删第一个"apple"
print(fruits)  # 输出: ["banana", "apple"]

  1. pop(index=-1) 移除并返回指定索引的元素(默认移除最后一个元素)。

fruits = ["apple", "banana", "cherry"]
last = fruits.pop()  # 移除最后一个
print(last)  # 输出: "cherry"
print(fruits)  # 输出: ["apple", "banana"]

first = fruits.pop(0)  # 移除索引0的元素
print(first)  # 输出: "apple"

  1. clear()

fruits = ["apple", "banana"]
fruits.clear()
print(fruits)  # 输出: []

  1. del语句 不仅可删除元素,还可删除整个列表(通过索引或切片删除)。

fruits = ["apple", "banana", "cherry"]
del fruits[1]  # 删除索引1的元素
print(fruits)  # 输出: ["apple", "cherry"]

del fruits[1:]  # 删除从索引1到结尾的元素
print(fruits)  # 输出: ["apple"]

三、排序与反转

用于调整列表中元素的顺序:

  1. sort(key=None, reverse=False) 对列表原地排序(直接修改原列表,不返回新列表):
  • reverse=False(默认):升序;reverse=True:降序。
  • key:指定排序依据(如key=len按字符串长度排序)。

numbers = [3, 1, 4, 2]
numbers.sort()  # 升序排序
print(numbers)  # 输出: [1, 2, 3, 4]

numbers.sort(reverse=True)  # 降序排序
print(numbers)  # 输出: [4, 3, 2, 1]

words = ["banana", "apple", "cherry"]
words.sort(key=len)  # 按长度排序
print(words)  # 输出: ["apple", "banana", "cherry"](长度5→6→6)

  1. reverse()

numbers = [1, 2, 3, 4]
numbers.reverse()
print(numbers)  # 输出: [4, 3, 2, 1]

四、查找与统计

用于查询元素的位置或出现次数:

  1. index(x, start=0, end=len(list)) 返回元素x在列表中第一次出现的索引(startend指定查找范围,若x不存在则报错)。

fruits = ["apple", "banana", "apple"]
print(fruits.index("apple"))  # 输出: 0(第一个"apple"的索引)
print(fruits.index("apple", 1))  # 输出: 2(从索引1开始找)

  1. count(x) 返回元素x在列表中出现的次数。

numbers = [1, 2, 2, 3, 2]
print(numbers.count(2))  # 输出: 3(数字2出现了3次)

五、复制列表

copy()

original = [1, 2, 3]
copy = original.copy()  # 等价于 original[:]
copy.append(4)
print(original)  # 输出: [1, 2, 3](原列表不变)
print(copy)      # 输出: [1, 2, 3, 4](新列表修改)

六、其他常用操作

  • 列表拼接:用+拼接两个列表(返回新列表,不修改原列表)。

a = [1, 2]
b = [3, 4]
c = a + b  # 等价于 a.extend(b) 的"非修改版"
print(c)  # 输出: [1, 2, 3, 4]

  • 列表重复:用*重复列表元素(返回新列表)。

a = [1, 2]
print(a * 3)  # 输出: [1, 2, 1, 2, 1, 2]

这些方法覆盖了列表的大部分日常操作,掌握它们能高效处理列表数据。实际使用时,注意区分“修改原列表”和“返回新列表”的方法(如sort()修改原列表,而sorted()函数返回新列表)。

举报

相关推荐

0 条评论