python 列表相关操作

    1. 访问元素

index(x):返回列表中第一个值为 x 的元素的索引。

python
fruits = ['apple', 'banana', 'cherry']
print(fruits.index('banana'))  # 输出: 1

count(x):返回列表中值为 x 的元素的个数。

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

in 关键字:用于检查某个元素是否在列表中。

python
fruits = ['apple', 'banana', 'cherry']
print('banana' in fruits)  # 输出: True
    1. 修改列表

append(x):在列表末尾添加元素 x。

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

extend(iterable):在列表末尾追加可迭代对象中的元素。

python
fruits = ['apple', 'banana', 'cherry']
fruits.extend(['orange', 'grape'])
print(fruits)  # 输出: ['apple', 'banana', 'cherry', 'orange', 'grape']

insert(i, x):在索引 i 处插入元素 x。

python
fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, 'orange')
print(fruits)  # 输出: ['apple', 'orange', 'banana', 'cherry']

remove(x):移除列表中第一个值为 x 的元素。

python
fruits = ['apple', 'banana', 'cherry']
fruits.remove('banana')
print(fruits)  # 输出: ['apple', 'cherry']

pop(i):移除并返回指定索引处的元素,默认为末尾元素。

python
fruits = ['apple', 'banana', 'cherry']
removed_fruit = fruits.pop(1)
print(removed_fruit)  # 输出: 'banana'
print(fruits)  # 输出: ['apple', 'cherry']

clear():移除列表中的所有元素。

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

reverse():反转列表中的元素顺序。

python
fruits = ['apple', 'banana', 'cherry']
fruits.reverse()
print(fruits)  # 输出: ['cherry', 'banana', 'apple']

sort(key=None, reverse=False):对列表进行排序,可指定排序键和排序顺序。

python
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]
numbers.sort()
print(numbers)  # 输出: [1, 1, 2, 3, 4, 5, 5, 6, 9]
    1. 其他操作

copy():返回列表的浅拷贝。

python
fruits = ['apple', 'banana', 'cherry']
fruits_copy = fruits.copy()
print(fruits_copy)  # 输出: ['apple', 'banana', 'cherry']

len(list):返回列表中元素的个数。

python
fruits = ['apple', 'banana', 'cherry']
print(len(fruits))  # 输出: 3

slice 操作:用于获取列表的子列表,例如 list[start:end]。

python
numbers = [1, 2, 3, 4, 5]
sliced_numbers = numbers[1:4]
print(sliced_numbers)  # 输出: [2, 3, 4]
    1. 列表操作

'+' 运算符:用于连接两个列表,返回一个新列表。

python
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print(combined_list)  # 输出: [1, 2, 3, 4, 5, 6]

这些例子展示了每个列表操作的基本用法和效果。通过实际运行这些代码,你可以更好地理解每个函数的作用和效果。
感谢gpt

posted on 2024-06-30 20:55  阿斯利康闪电  阅读(1)  评论(0编辑  收藏  举报

导航