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

Python入门作业求助:如何将用户输入与列表索引关联截取指定区间

解决思路与代码修改

你当前代码里用random.choice()是随机选取单个颜色,和任务要求的“展示索引区间内的颜色列表”不符。要关联用户输入的索引和列表,直接用Python的列表切片就能实现。

修改后的基础代码

import random 
colour_list = ["red","blue","white","yellow","pink","orange","black","green","grey","purple"]
start_num = int(input("enter a starting number between 0 and 4\n"))
end_num = int(input("enter a end number between 5 and 9\n"))

# 利用切片获取区间内的颜色,注意Python切片是左闭右开,所以结束位置要+1
selected_colours = colour_list[start_num:end_num + 1]
print("Selected colours:", selected_colours)

关键说明

  • 列表切片的语法是列表[起始索引:结束索引],但这个区间是左闭右开的——也就是包含起始索引的元素,但不包含结束索引的元素。所以要想包含end_num对应的颜色,必须把切片的结束位置设为end_num + 1。
  • 举个例子:如果输入start_num=1、end_num=6,切片colour_list[1:7]会取出索引1到6的元素:["blue","white","yellow","pink","orange","black"]。

可选的输入验证优化

如果要避免用户输入不符合要求的数字(比如负数或超出范围的数),可以加个循环验证逻辑,让代码更健壮:

import random 
colour_list = ["red","blue","white","yellow","pink","orange","black","green","grey","purple"]

# 验证起始数字输入
while True:
    start_input = input("enter a starting number between 0 and 4\n")
    if start_input.isdigit():
        start_num = int(start_input)
        if 0 <= start_num <= 4:
            break
    print("输入无效,请输入0到4之间的数字。")

# 验证结束数字输入
while True:
    end_input = input("enter a end number between 5 and 9\n")
    if end_input.isdigit():
        end_num = int(end_input)
        if 5 <= end_num <= 9:
            break
    print("输入无效,请输入5到9之间的数字。")

selected_colours = colour_list[start_num:end_num + 1]
print("Selected colours:", selected_colours)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 22:45:32