python function 增删改查
时间: 2024-04-24 11:18:39 浏览: 79
Python面向对象之类和对象属性的增删改查操作示例
在Python中,可以使用函数来实现增删改查的操作。下面是一个简单的示例代码来演示Python函数的增删改查操作:
1. 增加数据:
```python
def add_data(data_list, new_data):
data_list.append(new_data)
return data_list
data_list = [1, 2, 3, 4]
new_data = 5
result = add_data(data_list, new_data)
print(result) # 输出:[1, 2, 3, 4, 5]
```
2. 删除数据:
```python
def delete_data(data_list, target_data):
if target_data in data_list:
data_list.remove(target_data)
return data_list
data_list = [1, 2, 3, 4]
target_data = 3
result = delete_data(data_list, target_data)
print(result) # 输出:[1, 2, 4]
```
3. 修改数据:
```python
def update_data(data_list, target_data, new_data):
if target_data in data_list:
index = data_list.index(target_data)
data_list[index] = new_data
return data_list
data_list = [1, 2, 3, 4]
target_data = 3
new_data = 5
result = update_data(data_list, target_data, new_data)
print(result) # 输出:[1, 2, 5, 4]
```
4. 查询数据:
```python
def search_data(data_list, target_data):
if target_data in data_list:
return True
else:
return False
data_list = [1, 2, 3, 4]
target_data = 3
result = search_data(data_list, target_data)
print(result) # 输出:True
```
阅读全文