删除列表中的最大元素和最小元素
时间: 2024-05-15 20:15:57 浏览: 12
以下是Python代码实现:
```python
def remove_max_min(lst):
if len(lst) < 2:
return []
# 找到最大值和最小值的索引
max_index = lst.index(max(lst))
min_index = lst.index(min(lst))
# 删除最大值和最小值
if max_index > min_index:
del lst[max_index]
del lst[min_index]
else:
del lst[min_index]
del lst[max_index]
return lst
```
使用示例:
```python
lst = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
remove_max_min(lst)
# 输出:[3, 4, 5, 9, 2, 6, 5, 3, 5]
```
相关问题
python去除列表最大元素和最小元素
可以使用Python内置的min()和max()函数来找到列表中的最大值和最小值,然后再使用列表的remove()方法从列表中删除它们。
下面是一个示例代码:
```
my_list = [3, 5, 2, 8, 1, 9, 4]
# 找到最大值和最小值
max_num = max(my_list)
min_num = min(my_list)
# 从列表中删除最大值和最小值
my_list.remove(max_num)
my_list.remove(min_num)
print(my_list) # 输出: [3, 5, 2, 4, 9]
```
读入一个整数列表,输出删除最大元素和最小元素后的列表。最大元素和最小元素可能有多个。
以下是 Python 代码实现:
```python
lst = list(map(int, input().split()))
max_val = max(lst)
min_val = min(lst)
lst = [x for x in lst if x != max_val and x != min_val]
print(lst)
```
这段代码首先读入一个整数列表,然后找到列表中的最大值和最小值。接着使用列表推导式,将列表中不等于最大值和最小值的元素筛选出来,最后输出新的列表。