编写代码实现:删除列表中大于5的元素,lst = [2, 5, 6, 7, 3, 4, 10]
时间: 2023-10-06 16:14:01 浏览: 64
2.列表中删除多个元素
可以用列表推导式来实现删除大于5的元素:
```python
lst = [2, 5, 6, 7, 3, 4, 10]
lst = [x for x in lst if x <= 5]
print(lst)
```
运行结果为:
```
[2, 5, 3, 4]
```
也可以用循环和条件判断来实现:
```python
lst = [2, 5, 6, 7, 3, 4, 10]
new_lst = []
for x in lst:
if x <= 5:
new_lst.append(x)
print(new_lst)
```
运行结果也为:
```
[2, 5, 3, 4]
```
阅读全文