Python Forum

Full Version: list of list to list of tuple?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
network= [['0 1'], ['0 2'], ['0 3'], ['1 4'], ['1 6'], ['1 7'], ['1 9'], ['2 3'], ['2 6'], ['2 8'], ['2 9']]

I have a list of lists (above) and I am trying to create a list of tuples where it looks like this:

[(0, [1, 2, 3]), (1, [0, 4, 6, 7, 9]), (2, [0, 3, 6, 8, 9]),]

So far I have:
network= [['0 1'], ['0 2'], ['0 3'], ['1 4'], ['1 6'], ['1 7'], ['1 9'], ['2 3'], ['2 6'], ['2 8'], ['2 9']]
friends=[]

for i in range(len(network)):
    element= (network[i][0][0], i+1)
    friends.append(element)
print(friends)


And it outputs:
[('0', 1), ('0', 2), ('0', 3), ('1', 4), ('1', 5), ('1', 6), ('1', 7), ('2', 8), ('2', 9), ('2', 10), ('2', 11)]

I am unsure how to take the next step,plus this output is wrong, how do I convert this into what is expected

Please help
How do I convert this list of lists:

[['0', '1'], ['0', '2'], ['0', '3'], ['1', '4'], ['1', '6'], ['1', '7'], ['1', '9'], ['2', '3'], ['2', '6'], ['2', '8'], ['2', '9']]

To this list of tuples:

[(0, [1, 2, 3]), (1, [0, 4, 6, 7, 9]), (2, [0, 3, 6, 8, 9])]

I am unsure how to implement this next step? (I can't use dictionaries,
sets, deque, bisect module. You can though, and in fact should, use .sort or sorted functions.)

Here is my attempt:

    network= [['10'], ['0 1'], ['0 2'], ['0 3'], ['1 4'], ['1 6'], ['1 7'], ['1 9'], ['2 3'], ['2 6'], ['2 8'], ['2 9']]
    network.remove(network[0])
    friends=[]
    
    for i in range(len(network)):
        element= (network[i][0]).split(' ')
        friends.append(element)
    
    
    t=len(friends)
    lst=[]
    
    for i in range(t):
        a= (friends[i][0])
        if a not in lst:
            lst.append(int(a))
            for i in range(t):
                if a == friends[i][0]:
                    b=(friends[i][1])
                    lst.append([b])
    print(tuple(lst))
It outputs:

  (0, ['1'], ['2'], ['3'], 0, ['1'], ['2'], ['3'], 0, ['1'], ['2'], ['3'], 1, ['4'], ['6'], ['7'], ['9'], 1, ['4'], ['6'], ['7'], ['9'], 1, ['4'], ['6'], ['7'], ['9'], 1, ['4'], ['6'], ['7'], ['9'], 2, ['3'], ['6'], ['8'], ['9'], 2, ['3'], ['6'], ['8'], ['9'], 2, ['3'], ['6'], ['8'], ['9'], 2, ['3'], ['6'], ['8'], ['9'])
I am very close it seems, but not sure what to do??
sort the list by the first element, then loop over it and check what the first element in each sub-list is. if it is different from the [first] one in the previous sub-list  - add new element in the result list and start populating it