欢迎访问宙启技术站
智能推送

Python函数之列表操作:增、删、改、查

发布时间:2023-06-27 06:04:15

Python中,列表是一种非常常用的数据类型。它可以容纳任何类型的数据,并且可以进行许多有用的操作。其中,增、删、改、查是列表操作中最基本的几个。

1. 列表的增加操作

列表的增加操作主要包括两个:append()和extend()。

(1)append() 方法

append()方法用于在列表的末尾添加新的元素。它只接受一个参数,即要添加到列表中的新元素。例如:

fruits = ['apple', 'banana', 'cherry']
fruits.append('orange')
print(fruits)   # ['apple', 'banana', 'cherry', 'orange']

(2)extend() 方法

extend()方法用于将一个列表中的所有元素添加到另一个列表的末尾。它接受一个参数,即要添加到列表中的新元素的列表。例如:

fruits = ['apple', 'banana', 'cherry']
more_fruits = ['orange', 'lemon', 'grape']
fruits.extend(more_fruits)
print(fruits)   # ['apple', 'banana', 'cherry', 'orange', 'lemon', 'grape']

2. 列表的删除操作

列表的删除操作主要包括三个:pop()、remove()和del。

(1)pop() 方法

pop()方法用于从列表中删除指定位置的元素,并返回该元素的值。如果不指定位置,它将删除列表中的最后一个元素。例如:

fruits = ['apple', 'banana', 'cherry']
print(fruits.pop(1))    # 'banana'
print(fruits)   # ['apple', 'cherry']

(2)remove() 方法

remove()方法用于从列表中删除指定的元素。如果该元素在列表中存在多次,它只会删除第一个。如果要删除所有的该元素,可以使用循环。例如:

fruits = ['apple', 'banana', 'cherry', 'banana']
fruits.remove('banana')
print(fruits)   # ['apple', 'cherry', 'banana']

(3)del 方法

del方法用于删除列表中指定位置的元素,或者整个列表。例如:

fruits = ['apple', 'banana', 'cherry']
del fruits[1]
print(fruits)   # ['apple', 'cherry']

del fruits   # 删除整个列表

3. 列表的修改操作

列表的修改操作其实就是对列表中的元素进行重新赋值。

fruits = ['apple', 'banana', 'cherry']
fruits[1] = 'orange'
print(fruits)   # ['apple', 'orange', 'cherry']

4. 列表的查询操作

列表的查询操作主要有两种:按索引查询和使用 in 运算符查询。

(1)按索引查询

使用列表的索引值可以查询列表中的元素。例如:

fruits = ['apple', 'banana', 'cherry']
print(fruits[1])    # 'banana'

(2)使用 in 运算符查询

使用 in 运算符可以快速地判断指定的元素是否在列表中。例如:

fruits = ['apple', 'banana', 'cherry']
if 'banana' in fruits:
    print('Yes')
else:
    print('No')

以上就是Python中的列表操作中最基本的几个。在使用列表时,还可以使用许多其他的操作,如排序、反转等等。但在日常使用中,上述四个最基本的操作足以满足大部分需求。