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

Python三元列表如何获取大小处于中间位置的元素对应的索引

报错原因

  • 核心语法问题:Python 3中print为内置函数,调用必须添加括号,你代码中的print lst.index(x)属于Python 2的语法,修改为print(lst.index(x))即可解决直接报错问题。
  • 潜在逻辑缺陷:你当前的判断条件冗余且在存在重复元素时会失效,且list.index()方法只会返回第一个匹配元素的索引,遇到重复的中间值会返回错误结果。

优化实现方案

你的场景固定是3元素列表,推荐用更简洁的索引映射排序方案,无需复杂判断,兼容重复元素场景:

# 一行完成3个元素的输入
lst = [int(input("Enter elements of the list: ")) for _ in range(3)]
# 打包原始索引和值后按值排序,取排序后的第二位的原始索引
mid_index = sorted(enumerate(lst), key=lambda item: item[1])[1][0]
print(f"中间值的索引为:{mid_index}")

如果你想保留原有循环写法,也可以简化判断逻辑,直接遍历索引+值避免查找索引的异常:

lst = []
for i in range(3):
    ele = int(input("Enter elements of the list: "))
    lst.append(ele)

min_val = min(lst)
max_val = max(lst)
for idx, val in enumerate(lst):
    if min_val < val < max_val:
        print(idx)
        break
# 处理元素重复的特殊场景
else:
    print(0)

内容的提问来源于stack exchange,提问作者Срђан Станишић

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 04:51:03