Unpacking the list of tuples from the list (s)

I have a list of tuples where one of the elements in the tuple is a list.

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

I would like to get only a list of tuples

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

This question seems to address the issue with tuples, but I'm worried that my use case has a lot more elements in the internal list and

[(a, b, c, d, e) for [a, b, c], d, e in example]

seems tedious. Is there a better way to write this?

+4
source share
3 answers

Tuples can be combined with +similar lists. So you can do:

>>> example = [([0, 1, 2], 3, 4), ([5, 6, 7], 8, 9)]
>>> [tuple(x[0]) + x[1:] for x in example]
[(0, 1, 2, 3, 4), (5, 6, 7, 8, 9)]

Note that this works in both Python 2.x and 3.x.

+5
source

In Python3, you can also:

[tuple(i+j) for i, *j in x]

if you do not want to indicate every part of your input

+4

:

from itertools import chain

def to_iterable(x):
    try:
        return iter(x)
    except TypeError:
        return x,

example = [([0, 1, 2], 3, 4), ([5, 6, 7], 8, 9)]
output = [tuple(chain(*map(to_iterable, item))) for item in example]

:

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

This is more verbose than other solutions, but has the neat advantage of working regardless of the position or number of lists in internal tuples. Depending on your requirements, this may be an excessive or a good solution.

+2
source

Source: https://habr.com/ru/post/1589051/


All Articles