My goal is to take lists that contain strings such as ['1 0', '2 0', '3 1 2'] or [['1 0'], ['2 0'], ['3 1 2']]
and turn that into an adjacency list like so: [[1, 0], [2,0], [3,1], [3,2]]
The issue I have is that the last string in the list has more than two digits ['3 1 2']. This causes unpacking the sublist to generate the error shown below:
Traceback (most recent call last):
File "/tmp/source.py", line 79, in <module>
for dest, src in nlist:
ValueError: too many values to unpack (expected 2)
Code so far:
linelist: ['1 0', '2 0', '3 1 2']
newlist = []
print("linelist1", linelist)
for word in linelist:
word = word.split(",")
newlist.append(word)
newlist: [['1 0'], ['2 0'], ['3 1 2']]
adj_list = {}
nlist = []
for inner_list in newlist:
values = [int(x) for x in inner_list[0].split()] # splits each sublist
nlist.append(values)
adj_list [values[1]] = values[0:]
adj_list = defaultdict(list)
for dest, src in nlist:
adj_list[src].append(dest)
Should output: [[1, 0], [2,0], [3,1], [3,2]]