2016-08-24 52 views
-3

這段代碼在我使用我早期的一組數據時工作得很好。但是,現在我已經添加了更多的列到輸入數據集,我正在索引錯誤。我不完全確定如何解決這個問題。任何投入? 。下面的代碼是給我的錯誤:Python:IndexError:列表索引變形

with open("master_aggregated_monthly.csv", 'rb') as csvfile: 
    data_reader = csv.reader(csvfile, delimiter = ',', quotechar = '"') 
    rolling_queue = [] 
    for row in data_reader: 
     if row[0].lower() == "salesforceid": 
      continue 

     # most recent rows go in first 
     rolling_queue.insert(0,row) 
     if len(rolling_queue) > 12: 
      rolling_queue.pop() 

     id = row[0] 
     date = row[2] 
     if id in company_dictionary: 
      account = company_dictionary[id] 
      #See if we are at the final event 
      #get the final event from the list 
      # most recent date for data collection 
      if date == "6/1/2016": 
       new_event = event() 
       new_event.date = "7/1/2016" 
       new_event.type = "Current Period" 
       account.events.append(new_event) 
       my_event = account.events[0] 
       for entry in rolling_queue: 
       # don't do anything if the entry in the rolling queue is not from the same account 
        if entry[0] != id: 
         continue 

        nonzero_row = False 
        # loop through the entries in the rolling queue to find at most the last 12 months of data 
        for i in range(3, len(entry)): 
         try: 
          my_event.attributes[i-3] += float(entry[i]) 
         except: 
          #handle all of the odd string things 
          temp = entry[i].split(' ') 
          if temp[0] == '': 
           temp = float(temp[1]) 
          else: 
           temp = float(temp[0]) 
          my_event.attributes[i-3] += temp 
         # discover if this row is nonzero 
         if entry[i] != 0 and entry[i] != '0': 
          nonzero_row = True 
        # don't include this rown in the average if it's a zero row 
        if nonzero_row: 
         #print "Month increment" 
         my_event.months += 1 

此代碼是給我下面的錯誤

<type 'exceptions.IndexError'> 
Traceback (most recent call last): 
    File "P:/Testing/The Scripts, JIC Test/Q4_12month.py", line 116, in main 
    my_event.attributes[i-3] += temp 
IndexError: list index out of range 
+2

http://stackoverflow.com/help/mcve –

+0

你應該斷點行116,看看my_event.attributes實際包含的內容 –

+0

你應該花一些時間和正確格式化這篇文章(你的代碼特別是,因爲它是Python) 。其次,您需要拉出並突出顯示您遇到問題的特定行(我們如何知道第116行的引用?),並且最好是最小的,可驗證的完整示例。有關更多信息,請參見[sscce](http://www.sscce.org)。 –

回答

0

你基於關閉的entry長度創建索引,但使用該索引中my_event.attributes

for i in range(3, len(entry)): 
    ... 
    except: 
     ... 
     my_event.attributes[i-3] += temp 
     ... 
    ... 

這可能是問題所在,但要告訴你的代碼在做什麼很難。一般來說,你只需要在索引創建的任何對象上使用/索引應該引用的任何對象(在本例中爲entry)。

+0

謝謝@zaychee。任何解決這個問題的建議? –

+0

'len(entry)'和'my_event.attributes'如何相關? – zachyee