0
import math

def getBestLoc(lst):
    if len(lst) % 2 == 0:
        #bestLoc = (lst((len(lst)/2) + lst(len(lst)/2)-1))/2
        bestLoc = ((lst[len(lst)]//2) + (lst[len(lst)/2]-1)) // 2
    else:
        bestLoc = lst(len(lst)//2)
    sumOfDistances(lst, bestLoc)
    return bestLoc

def sumOfDistances(lst, bestLoc):
    total = 0
    for i in lst:
        total += math.abs(bestLoc - i)
    return total

def main():
    lst = [10, 15, 30, 200]
    lst.sort()
    print(lst)
    getBestLoc(lst)

main()

我收到了这个错误:

Traceback (most recent call last):
  File "C:\Users\NAME\Desktop\storeLocation.py", line 32, in <module>
    main()
  File "C:\Users\NAME\Desktop\storeLocation.py", line 30, in main
    getBestLoc(lst)
  File "C:\Users\NAME\Desktop\storeLocation.py", line 14, in getBestLoc
    bestLoc = ((lst[len(lst)]//2) + (lst[len(lst)/2]-1)) // 2
IndexError: list index out of range

我不知道我做错了什么。它是说,,IndexError: list index out of range我不知道那是什么意思。这是我的实验室作业。试图弄清楚这个问题。有什么帮助吗?谢谢。

4

4 回答 4

4

您需要使用 访问列表的元素[],而不是使用 将其作为函数调用()。代替:

bestLoc = ((lst(len(lst))/2) + (lst(len(lst)/2)-1)) / 2

bestLoc = ((lst[len(lst)]/2) + (lst[len(lst)/2]-1)) / 2
于 2013-10-08T22:19:59.727 回答
2

访问列表元素使用方括号 [] 而不是 ()

应该

((lst[len(lst)]/2) + (lst[len(lst)/2]-1)) / 2

与 else: 子句相同

于 2013-10-08T22:19:32.833 回答
2

您正在尝试lst通过使用lst(...). 尝试使用方括号lst[...]

于 2013-10-08T22:20:29.103 回答
1

其他海报怎么说。使用方括号[]而不是圆括号()来访问列表元素。例如。lst[index] 此外,您正在尝试访问列表之外的元素。

不要使用lst[len(lst)]- 您会自动获取索引越界异常。相反,使用lst[len(lst)-1].

另外,不要使用 math.abs,该函数在 python 中不存在。而是使用 math.fabs

于 2013-10-08T22:25:54.553 回答