Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get ['1 0', '2 0', '3 1 2'] to be [[1, 0], [2,0] , [3,1] , [ 3,2] ] in so I can unpack the values. Python. Adjacency list

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]]

>Solution :

You can try:

lst = ["1 0", "2 0", "3 1 2"]

out = []
for s in lst:
    n, *rest = map(int, s.split())
    out.extend([n, v] for v in rest)

print(out)

Prints:

[[1, 0], [2, 0], [3, 1], [3, 2]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading