简体   繁体   English

由于列表索引超出范围而出现错误

[英]getting error as list index out of range

I have the following program to calculate the percentage of CO2 every year. 我有以下程序来计算每年的CO2百分比。 I get an error, "list index out of range" , once the entire program runs on the following line: 整个程序在以下行中运行后,出现错误“列表索引超出范围”

m= co2level[i+1][1] 

Code: 码:

# 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

You could avoid the bounds error like this: 您可以这样避免边界错误:

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

You start with the 1st year you can get a "delta" for and inspect the one before this. 从第一年开始,您可以得到一个“增量”,并在此之前进行检查。 You compare act to old so you are not going over the bound. 您将行为与古老相提并论,因此您不会越界。

Python is 0 indexed; Python的索引为0; that means for a list with n elements, the first element of a list is at index 0 and the last element is at index n - 1 这意味着对于具有n个元素的列表,列表的第一个元素在索引0处,最后一个元素在索引n-1处

Consider the following snippent from your code: 请考虑以下代码片段:

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

The line m = co2level[i+1][1] implies that you start iterating from the element at index 1 (2003,322.16) and tries to get the item at index 6 at the end which causes the error. m = co2level[i+1][1]表示您从索引1 (2003,322.16)的元素开始迭代,并尝试在导致错误的末尾获取索引6的项。 Morover you have an error in how you assigned m and n . 更何况,您在分配mn出错。 To correct this you can do: 要更正此问题,您可以执行以下操作:

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

The more pythonic way (using for loops) will be 更加Python化的方式(用于循环)将是

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

better still: 更好的是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM