列表索引超出范围

时间:2016-12-10 08:17:06

标签: python

我有一对单词列表,我正在尝试将它们准备为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]})

2 个答案:

答案 0 :(得分: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;访问:3',' parttim; site :4',' parttim; uncl:0',' parttim; home:5',' parttim; onlin:1']

  

答案 1 :(得分:-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}]