How to flatten inner tuples in a list containing tuples of a two-item tuple and a single item

Viewed 68

I want to know if there is any efficient way to convert a list containing tuples of a two-item tuple and a single item into a flattened list or NumPy array?

list = [((-1, -1), -1), ((-1, -1), 0), ((-1, -1), 1), ((-1, -1), 2), ...]

The result I want is:

new_list = [[-1, -1, -1], [-1, -1, 0], [-1, -1, 1], [-1, -1, 2], ...]

So far, I have tried to use

new_list = [item for i in list for item in i]

But the result is comes out as:

[(-1, -1), -1, (-1, -1), 0, (-1, -1), 1, (-1, -1), 2, ...]

When I tried to remove the nested tuple, I got the error

TypeError: 'int' object is not iterable
4 Answers

Since the structure of each of the tuples seems to be ((a, b), c), you can just use a list comprehension with tuple-unpacking:

>>> lst = [((-1, -1), -1), ((-1, -1), 0), ((-1, -1), 1), ((-1, -1), 2)]
>>> [[a, b, c] for ((a, b), c) in lst]
[[-1, -1, -1], [-1, -1, 0], [-1, -1, 1], [-1, -1, 2]]

Just a shorter one:

[[*x, y] for x, y in lst]

You need to keep the structure of the list (more or less). You're really flattening the nested elements, not the list itself. Unpacking is one simple way to go

new_lst = [[*x[0], x[1]] for x in lst]

Another is just explicit references:

new_lst = [[x[0][0], x[0][1], x[1]] for x in lst]

This should work assuming x = [((-1, -1), -1), ((-1, -1), 0), ((-1, -1), 1), ((-1, -1), 2), ...]

new_list = [list(i[0])+[i[1]] for i in x]
Related