编写一个Python函数`list_max()`,接受一个整数列表作为输入参数。该函数需要返回列表中最大值和最小值。
时间: 2024-05-15 13:17:22 浏览: 130
好的,这个问题是计算相关的,可以回答。下面是Python代码实现:
```python
def list_max(lst):
max_val = lst[0]
min_val = lst[0]
for x in lst:
if x > max_val:
max_val = x
if x < min_val:
min_val = x
return max_val, min_val
```
这个函数接受一个整数列表作为输入参数,返回列表中的最大值和最小值,使用方法如下:
```python
lst = [3, 5, 1, 8, 2, 9]
max_val, min_val = list_max(lst)
print("最大值:", max_val)
print("最小值:", min_val)
```
输出结果如下:
```
最大值: 9
最小值: 1
```
相关问题
如何用Python编写一个函数,该函数接收一个整数列表作为输入,然后返回列表中最大值及其对应的索引,以及最小值及其对应的索引?
在Python中,你可以通过定义一个名为`find_max_min_indices`的函数来实现这个功能。这里是一个示例代码:
```python
def find_max_min_indices(numbers):
if not numbers: # 检查列表是否为空
return "List is empty"
max_value = max(numbers)
min_value = min(numbers)
max_index = numbers.index(max_value) # 使用index()获取最大值的索引
min_index = numbers.index(min_value) # 同样,获取最小值的索引
return {"max": max_value, "max_index": max_index, "min": min_value, "min_index": min_index}
# 测试函数
input_list = [1, 5, 3, 9, 2]
result = find_max_min_indices(input_list)
print(f"Max value: {result['max']}, Index: {result['max_index']}")
print(f"Min value: {result['min']}, Index: {result['min_index']}")
```
这个函数首先检查输入列表是否为空,然后分别计算最大值和最小值,并找到它们在列表中的索引。最后,它会以字典的形式返回结果。
创建一个函数my_max,实现从键盘输入五个整数,返回这些数中的最大值
好的,下面是一个实现该功能的 Python 函数:
```python
def my_max():
num_list = []
for i in range(5):
num = int(input("请输入第 %d 个整数:" % (i+1)))
num_list.append(num)
max_num = num_list[0]
for num in num_list:
if num > max_num:
max_num = num
return max_num
```
这个函数首先从键盘输入五个整数,然后遍历这个列表找到最大的数,最后返回最大值。
你可以在 Python 环境中调用这个函数来测试它的效果,例如:
```python
max_num = my_max()
print("最大值为:", max_num)
```
当然,这只是一个简单的实现,如果你希望函数更加健壮,可以添加一些判断,例如输入的是否为整数等。
阅读全文
相关推荐
















