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

Python如何获取从1开始计数的指定索引对应的列表元素值

实现按1起始索引查询对应因数的方案

调整思路

  • 原有函数仅支持打印全量索引和因数,首先修改函数逻辑,将计算得到的因数列表作为返回值输出,方便后续按索引取值
  • 由于Python列表默认从0开始计数,输入的1起始索引需要减去1才能匹配列表的实际下标
  • 补充索引合法性校验,避免输入的索引超出因数总数时抛出下标越界异常

调整后代码

def get_factors(x):
    arr = []
    for i in range(1, x+1):
        if x % i == 0:
            arr.append(i)
    return arr

def get_factor_by_index(num, index):
    factors = get_factors(num)
    # 校验索引合法性
    if 1 <= index <= len(factors):
        return factors[index-1]
    else:
        return f"索引无效,当前数字共有{len(factors)}个因数,索引范围为1~{len(factors)}"

# 测试示例
num = 10
print(get_factor_by_index(num, 3)) # 输出 5
print(get_factor_by_index(num, 4)) # 输出 10
print(get_factor_by_index(num, 5)) # 输出 索引无效,当前数字共有4个因数,索引范围为1~4

动态输入适配

如果需要接收用户实时输入的数字和查询索引,可补充如下逻辑:

num = int(input("请输入要计算因数的数字:"))
input_index = int(input("请输入要查询的1起始索引:"))
print(get_factor_by_index(num, input_index))

内容的提问来源于stack exchange,提问作者Parth Bhavsar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 07:24:06