python列表增删改查
时间: 2023-09-20 22:11:14 浏览: 46
1. 增加元素:
a. append()方法:在列表末尾添加一个元素。
```
fruits = ['apple', 'banana']
fruits.append('orange')
print(fruits) # ['apple', 'banana', 'orange']
```
b. insert()方法:在指定位置插入一个元素。
```
fruits = ['apple', 'banana']
fruits.insert(1, 'orange')
print(fruits) # ['apple', 'orange', 'banana']
```
c. extend()方法:将一个列表的元素添加到另一个列表的末尾。
```
fruits1 = ['apple', 'banana']
fruits2 = ['orange', 'kiwi']
fruits1.extend(fruits2)
print(fruits1) # ['apple', 'banana', 'orange', 'kiwi']
```
2. 删除元素:
a. remove()方法:删除列表中的指定元素。
```
fruits = ['apple', 'banana', 'orange']
fruits.remove('banana')
print(fruits) # ['apple', 'orange']
```
b. pop()方法:删除列表中指定位置的元素。
```
fruits = ['apple', 'banana', 'orange']
fruits.pop(1)
print(fruits) # ['apple', 'orange']
```
c. del语句:删除列表中指定位置的元素或整个列表。
```
fruits = ['apple', 'banana', 'orange']
del fruits[1]
print(fruits) # ['apple', 'orange']
del fruits
print(fruits) # NameError: name 'fruits' is not defined
```
3. 修改元素:
a. 直接赋值:通过索引直接修改列表中的元素。
```
fruits = ['apple', 'banana', 'orange']
fruits[1] = 'kiwi'
print(fruits) # ['apple', 'kiwi', 'orange']
```
b. 切片赋值:通过切片修改列表中的一部分元素。
```
fruits = ['apple', 'banana', 'orange']
fruits[1:3] = ['kiwi', 'grape']
print(fruits) # ['apple', 'kiwi', 'grape']
```
4. 查找元素:
a. in关键字:判断一个元素是否在列表中。
```
fruits = ['apple', 'banana', 'orange']
print('apple' in fruits) # True
print('kiwi' in fruits) # False
```
b. index()方法:获取一个元素在列表中的索引。
```
fruits = ['apple', 'banana', 'orange']
print(fruits.index('banana')) # 1
```