Home > Enterprise >  How can I convert this [['1 0'], ['2 0'], ['3 1 2']] into an adjacency
How can I convert this [['1 0'], ['2 0'], ['3 1 2']] into an adjacency

Time:11-11

I have a list of the lists that contain strings, like so :

[['1 0'], 
['2 0'], 
['3 1 2']]  

How can I convert it to an adjacency list in Python please like this: (all ints)

{ 
1: 0, 
2:0, 
3: 1,2 
}

My attempts so far have gotten me to this:

newlist = []
for word in linelist:
    word = word.split(",")
    newlist.append(word)
print(newlist)

which produces this:

[['1 0'], 
 ['2 0'], 
 ['3 1 2']]  

Thanks very much!

CodePudding user response:

You can convert it to a dict with something like this:

adj_dict = {}
for inner_list in outer_list:
    values = [int(x) for x in inner_list[0].split()]
    adj_dict[values[0]] = values[1:]

CodePudding user response:

It kind of depends on the data types you want for the values in the dictionary, but this should get you most of the way there:

res = {}
for e in a:
    res[e[0][0]] = ','.join(e[0][1::].strip().split(' '))

CodePudding user response:

You can use a nested comprehension combined with list slices like this:

>>> s = [['1 0'], 
... ['2 0'], 
... ['3 1 2']]
>>> 
>>> [{_[0]: _[1:]} for _ in [list(map(int, _[0].split())) for _ in s]]
[{1: [0]}, {2: [0]}, {3: [1, 2]}]

We can also make it a bit shorter, using the * operator:

>>> [{_[0]: _[1:]} for _ in [[*map(int, _[0].split())] for _ in s]]
[{1: [0]}, {2: [0]}, {3: [1, 2]}]
  • Related