2016-12-10 35 views
0

我有一對單詞列表,並試圖將它們準備爲NetworkX讀取的數據。部分腳本遍歷這些對以將它們映射到id號碼(請參閱下面的代碼)。這段代碼會拋出一個Index out of range-我需要過去的錯誤。這裏有什麼錯誤?列表索引超出範圍

coocs = [['parttim;work'], ['parttim;work'],['parttim;visit'], ['parttim;site'], ['parttim;uncl'], ['parttim;home'], ['parttim;onlin']] 
unique_coocs = list(set([row[0] for row in coocs])) # remove redundance 
ids = list(enumerate(unique_coocs)) # creates a list of tuples with unique ids and their names for each word in the network 
keys = {name: i for i, name in enumerate(unique_coocs)} # creates a dictionary(hash map) that maps each id to the words 
links = [] # creates a blank list 

for row in coocs: # maps all of the names in the list to their id number 
    try: 
     links.append({keys[row[0]]: keys[row[1]]}) 
    except: 
     links.append({row[0]: row[1]}) 
+0

什麼線路上的錯誤? –

+0

This:'links.append({row [0]:row [1]})' – textnet

+0

這將有助於給出整個錯誤信息。 – Joel

回答

-1

這工作得很好

for row in coocs: # maps all of the names in the list to their id number 
    links.append({row[0]: keys[row[0]]}) 

>>> links 
[{'parttim;work': 2}, {'parttim;work': 2}, {'parttim;visit': 3}, {'parttim;site': 4}, {'parttim;uncl': 0}, {'parttim;home': 5}, {'parttim;onlin': 1}] 
0

錯誤發生在row,因爲len(row)中總是1這裏,所以你不能使用index number 1這是row[1]

更正代碼是,

for row in coocs: 
    links.append(row[0]+':'+str(keys[row[0]])) 
print links 

輸出:

['parttim; work:2','parttim; work:2','parttim; visit 3','parttim; site:4','parttim; uncl:0','parttim; home:5' 'parttim; ONLIN:1']