【问题标题】:getting list index out of range error when trying to add a a number from a list into a another list尝试将列表中的数字添加到另一个列表中时出现列表索引超出范围错误
【发布时间】:2020-05-05 01:01:04
【问题描述】:
Gudi = 0
gudi = []
Numbers = []
A = int(input("how many numbers are in the list"))
time.sleep(.5)
print ("Can you please enter the numbers?")
time.sleep(.3)
for i in range(A):
  data = int(input())
  Numbers.append(data)

# variables
median = sorted(Numbers)
ludi = int(A/2) 
two = ludi - 1
One = median[ludi]
Two = median[two]
sum = (One + Two)
Ans = sum/2
cal = int((A - 1)/2 + 1) - 1
ans = median[cal]

def Median():
  if A%2 == 0:
     print ("The median is " + str(Ans))
  else:
     print ("The median is " + str(ans))


 def sorlist():
   print median

 def Maximum():
   print (median[-1])


 def Minimum():
   print (median[0])


 def UQ():
   if A%2 != 0:
      global Gudi
      global cal # the indice of the median
      var = A - (cal - 1) # number of numbers that come after the median
      Gudi += 1
      for i in range(var):
        cal += Gudi
        gudi.append(median[cal])
        Gudi += 1
 UQ()

当我尝试运行名为 UQ 的最后一个函数时,我收到此错误:“IndexError: list index out of range on line 50 in main.py”。我不知道出了什么问题。我正在尝试将列表的编号打印到另一个列表中,以便找到上四分位数。

【问题讨论】:

    标签: python


    【解决方案1】:

    问题出在这里

     for i in range(var):
        cal += Gudi
        gudi.append(median[cal])
        Gudi += 1
    

    在每次迭代中

    1. 你正在添加 Gudi 的 cal
    2. 古地增加1

    假设 A = 10

    cal = int((A - 1)/2 + 1) - 1 = 4

    var = 10 - (4- 1) = 5

    什么时候

    i=0,cal = cal + gudi = 4 + 1 = 5,gudi = 2

    i=1,cal = cal + gudi = 5 + 2 = 7,gudi = 3

    i=2, cal = cal + gudi = 7 + 3 = 10, Gudi = 4 --> 越界

    【讨论】:

    • 那么我该如何解决这个问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 2019-09-06
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多