2016-12-10 10 views
0

Ich habe eine Liste von Wortpaaren und versuche, sie als Daten für NetworkX zum Lesen vorzubereiten. Ein Teil des Skripts besteht darin, über die Paare zu iterieren, um sie den ID-Nummern zuzuordnen (siehe Code unten). Dieser Code löst einen Index out of range Fehler aus, den ich überwinden muss. Was ist der Fehler hier?Listenindex außerhalb des Bereichs

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

Welche Linie fein ist der Fehler auf? –

+0

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

+0

Es würde helfen, die gesamte Fehlermeldung zu geben. – Joel

Antwort

-1

Dies funktioniert

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

Fehler tritt bei row, weil len(row) in immer 1 hier, so dass Sie nicht die index number 1 die row[1]

ist

Corrected Code verwenden können,

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

Ausgang:

['parttim; Arbeit: 2', 'parttim; Arbeit: 2', 'parttim; Besuch: 3', 'parttim; Ort: 4', 'parttim; uncl: 0', 'parttim; Haus: 5' 'parttim; onlin: 1']

Verwandte Themen