【问题标题】:IndexError: list index out of range longitudeIndexError:列表索引超出范围经度
【发布时间】:2017-03-13 22:31:37
【问题描述】:

希望创建一个函数来读取具有纬度和经度的动物名称文件,然后它将返回设定区域内的#animals,但是我不断收到索引错误,我不知道为什么,我仍然Python 新手,只需要一点帮助 :')

def LocationCount(FileName, Distance, Lat2, Lon2):     
    List =[]                                                    
    File = open(FileName, "r")                                  
    for line in File:                                          
            List.append(LineToList(line))                       
    File.close()                                                

    List2 =[]
    ListCount = 0
    while ListCount <= len(List):
        if CalculateDistance(List[ListCount][1], List[ListCount][2], Lat2, Lon2) <= Distance:
            List2.append(line)
        ListCount += 1
    return(List2)

S = LocationCount("Mammal.txt", 10, 54.988056, -1.619444) 
print (len(List2))

【问题讨论】:

  • 您的主程序中没有变量 list2。您的函数有一个变量 list2,但在函数外部不可用。

标签: python list indexing index-error


【解决方案1】:

while ListCount &lt;= len(List):

改成,

while ListCount &lt; len(List): 列表索引为 0。

此外,您将值存储在 S 中并尝试打印在此范围内未定义的 list2。

S = LocationCount("Mammal.txt", 10, 54.988056, -1.619444) print (len(List2))

替换为,

S = LocationCount("Mammal.txt", 10, 54.988056, -1.619444) print len(S)

【讨论】:

  • 天哪,谢谢!解决了索引错误的问题,你是最棒的!但现在它说未定义列表 2 :') 我的代码是什么
  • @MichaelCooper:请查看更新后的答案。如果有帮助,也请接受答案。
猜你喜欢
  • 2011-10-31
  • 2015-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多