You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python不使用内置方法获取列表最值位置的问题求解

解决思路与代码修改

核心逻辑

要获取最值的位置,只需要在记录最值的同时同步记录对应的索引即可,完全不需要调用内置方法。具体步骤:

  • 新增两个变量high_index和low_index,专门用来存储最大值、最小值的索引位置
  • 第一次遍历(第一个元素)时,将这两个索引变量初始化为0(第一个元素的索引)
  • 后续遍历过程中,每当更新最大值或最小值时,同时把当前循环的索引赋值给对应的索引变量
  • 最后输出时,直接打印这两个索引变量就能得到最值的位置

修改后的完整代码

listone = [0] * 10

for c in range(0, 10):
    listone[c] = int(input('Type 10 values: '))
    if c == 0:
        # 同时初始化最值和对应的索引
        high = low = listone[c]
        high_index = low_index = c
    else:
        if listone[c] > high:
            high = listone[c]
            high_index = c  # 更新最大值的索引
        if listone[c] < low:
            low = listone[c]
            low_index = c  # 更新最小值的索引

print(f'The highest value typed was {high} at position {high_index}')
print(f'The lowest value typed was {low} at position {low_index}')

补充说明(处理多个相同最值的情况)

如果输入的列表中有多个相同的最大值或最小值,上面的代码只会记录最后一个出现的位置。如果需要收集所有出现的位置,可以用列表来存储索引:

listone = [0] * 10
high_indices = []
low_indices = []

for c in range(0, 10):
    listone[c] = int(input('Type 10 values: '))
    if c == 0:
        high = low = listone[c]
        high_indices.append(c)
        low_indices.append(c)
    else:
        if listone[c] > high:
            high = listone[c]
            high_indices = [c]  # 清空旧索引,记录新的最大值索引
        elif listone[c] == high:
            high_indices.append(c)  # 加入相同最大值的索引
        
        if listone[c] < low:
            low = listone[c]
            low_indices = [c]  # 清空旧索引,记录新的最小值索引
        elif listone[c] == low:
            low_indices.append(c)  # 加入相同最小值的索引

print(f'The highest value {high} appears at positions: {high_indices}')
print(f'The lowest value {low} appears at positions: {low_indices}')

内容的提问来源于stack exchange,提问作者Sarah Higgs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 03:35:31