【问题标题】:how can i get input while it show list out of index我如何在显示索引之外的列表时获取输入
【发布时间】:2021-08-16 03:09:54
【问题描述】:

代码->code 错误->error 我无法获取显示列表索引超出范围的输入

n = int(input())
a = []
temp = input().split()
for i in range(n):
    a.append(int(temp[i]))
print(a)

【问题讨论】:

  • 你为你的程序提供了哪些输入?
  • 我将整数作为输入
  • 你能举一个这些整数的具体例子吗?
  • nlen(temp) 需要对齐。目前看来你n 更大
  • @JonSG 是的,我确实返回了。刚才明白我需要用空格给输入,我做错的是我在给出第一个输入后按下了返回。谢谢你的回答 JonSG

标签: python python-3.x list arraylist


【解决方案1】:

这是你需要的吗?

n = int(input())
a = []
for i in range(n):
    a.append(int(input()))
print(a)

【讨论】:

  • 我知道这种方法。但我在在线测试中看到了上面的代码。当试图执行它时,它显示错误
【解决方案2】:

根据您输入的“4”和“2”, n = 4 温度 = [2]

那么,列表的长度为 1 长度(温度)= 1

我不确定你的代码到底需要什么,但你可以这样做:

n = int(input())
a = []
for i in range(min(n, len(temp))):
    a.append(int(input()))
print(a)

或者你也可以使用异常:

n = int(input())
a = []
for i in range(n):
    try:
        a.append(int(input()))
    except IndexError:
        break
print(a)

【讨论】:

    猜你喜欢
    • 2022-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-11
    相关资源
    最近更新 更多