获取错误作为列表索引超出范围

时间:2017-12-09 10:48:24

标签: python

我有以下计划来计算每年的二氧化碳百分比。 一旦整个程序在以下行上运行,我收到错误,“列表索引超出范围”

m= co2level[i+1][1] 

代码:

# Program to calculate percentage of CO2 every year     

co2level = [(2001,320.93),(2003,322.16),(2004,328.07),
             (2006,323.91),(2008,341.47),(2009,348.22)]
i = 0

while i!=len(co2level):

   m= co2level[i+1][1] # I am getting error here as list index out of range
   n= co2level[i][1]
   percentage=((m-n)/n)*100
   print " Change in percentage of CO2 in year %r is"%co2level[i][0],percentage

   i+=1

2 个答案:

答案 0 :(得分:0)

你可以避免这样的边界错误:

co2level = [(2001,320.93),(2003,322.16),(2004,328.07),
             (2006,323.91),(2008,341.47),(2009,348.22)]
i = 1

while i != len(co2level):
   old = co2level[i-1][1]
   act = co2level[i][1]

   percentage=((act-old)/old)*100
   print (" Change in percentage of CO2 in year %r is " %co2level[i][0],percentage)

   i+=1

从第一年开始,你可以得到一个" delta"在此之前检查并检查一个。你将行为与旧行进行比较,这样你就不会超越界限了。

答案 1 :(得分:0)

Python被索引为0;这意味着对于带有 n 元素的列表,列表的第一个元素位于索引0,最后一个元素位于索引 n - 1

从您的代码中考虑以下代码:

while i!=len(co2level):
   m= co2level[i+1][1] 

m = co2level[i+1][1]意味着您从索引1 (2003,322.16)处的元素开始迭代,并尝试在结尾处获取索引6处的项目,从而导致错误。 Morover,您分配mn的方式有误。要纠正这个问题,你可以这样做:

i = 0
while i!=len(co2level):
   m= co2level[i][0] # I am getting error here as list index out of range
   n= co2level[i][1]
   percentage=((m-n)/n)*100
   print" Change in percentage of CO2 in year %r is"%co2level[i][0],percentage
   i+=1

更多pythonic方式(使用for循环)将是

for i in co2level:
    m = i[0]
    n = i[1]
    percentage=((m-n)/n)*100
    print" Change in percentage of CO2 in year %r is"%co2level[i][0],percentage

更好的是:

for i in co2level:
    m, n = i
   percentage=((m-n)/n)*100
   print" Change in percentage of CO2 in year %r is"%co2level[i][0],percentage