Flatten a tuple inside a list that contains other type of object

Viewed 27

I have a list that is like a matrioska, fortunately it does attain to a format, which is [(),int]

Example:

    [[('spring', 'flowers'), 1], [('spring', 'birds'), 1], [('autumn', 'leaves'), 3],[('autumn', 'mild'), 1], [('summer', 'sun'), 2]]

I am trying to get this:

    [['spring', 'flowers', 1], ['spring', 'birds', 1], ['autumn', 'leaves', 3],['autumn', 'mild', 1], ['summer', 'sun', 2]]

I tried to unpack the tuple, using the formula:

   [(a, *rest) for a, rest in list]

And the error is: TypeError: 'int' object is not iterable

I also tried to separate the elements in sublists, but couldn't keep the order to bring them together again:

   season    = list(x[0] for x in info if isinstance(x,tuple))
   property  = list(x[1] for x in info if isinstance(x,tuple))
   times     = list(x for x in info if isinstance(x,int))
1 Answers

If the elements are syntactically equal, then you can use.

lst = [[('spring', 'flowers'), 1], [('spring', 'birds'), 1], [('autumn', 'leaves'), 3],[('autumn', 'mild'), 1], [('summer', 'sun'), 2]]

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

# [['spring', 'flowers', 1], ['spring', 'birds', 1], ['autumn', 'leaves', 3], ['autumn', 'mild', 1], ['summer', 'sun', 2]]
Related