Home > Back-end >  Converting list of lists of tuples to list of lists of lists
Converting list of lists of tuples to list of lists of lists

Time:08-27

I have this old random list:

old_list = [[(0, 1), (0, 2)], [(8, 4), (3, 7)]]

And I want to convert the tuples to lists like this :

>>> new_list = [[[0, 1], [0, 2]], [[8, 4], [3, 7]]]

I tried the below with a list comprehension, but apparently, it is wrong:

new_list = [list (y for y in x) for x in old_list]

CodePudding user response:

You can do this:

new_list = [[list(x) for x in y] for y in old_list]

which produces:

[[[0, 1], [0, 2]], [[8, 4], [3, 7]]]

CodePudding user response:

You need nested list comprehensions to create a nested result. The tuples that need to be converted to lists are at the second level down.

new_list = [[list(tup) for tup in level1] for level1 in old_list]

CodePudding user response:

That's what you do :)
list(np.array(old_list)

CodePudding user response:

You can convert to array with numpy module or you can simply just convert to list with list() method. Look for example:

Code Example

CodePudding user response:

This is the basic solution and there is no user of the extra list. I am updating the old_list :

for i in range(0, len(old_list)):
    for j in range(0, len(old_list[i])):
        old_list[i][j] = list(old_list[i][j])
print old_list

O/P

[[[0, 1], [0, 2]], [[8, 4], [3, 7]]]
  • Related