0

I have a list/tuple containing uneven sublists (query result from SQLAlchemy), which looks like this:

x = [('x', [1,2], [3,4])]

I want to unnest/explode x as the following:

x = [('x',[1],[3]),('x',[2],[4])]

Or

x = [('x',1,3),('x',2,4)]

I can achieve this using pandas dataframes with the following:

df = pd.DataFrame(x, columns=['X','A','B'])
df = df.apply(lambda x: x.explode() if x.name in ['A', 'B'] else x)
print([tuple(i) for i in df.values.tolist()])

which generates the following output:

[('x', 1, 3), ('x', 2, 4)]

However, I would love to know if there is any pure python only solution possible. I have been playing around with list comprehension based on following answer with no luck.

[item for sublist in x for item in sublist]

Any help would be appreciated.

Edit:

my input looks like this:

[(u'x.x@gmail.com', u'Contact Info Refused/Not provided was Documented', 0L, 
[None, None, None], [1447748, 1447751, 1447750], 3L, [1491930], 'nce', 1, 2037)]

Expected output:

Just unpacking two sublist and keep everything the same.

[(u'x.x@gmail.com',u'Contact Info Refused/Not provided was Documented','0L',None,1447748,3L,[1491930],'nce',1,2037),
,(u'x.x@gmail.com',u'Contact Info Refused/Not provided was Documented','0L',None,1447751,3L,[1491930],'nce',1,2037),
(u'x.x@gmail.com',u'Contact Info Refused/Not provided was Documented','0L',None,1447750,3L,[1491930],'nce',1,2037))    ]
Grayrigel
  • 3,474
  • 5
  • 14
  • 32

1 Answers1

1

From itertools

import itertools
list(itertools.zip_longest(*x[0],fillvalue=x[0][0]))
Out[25]: [('x', 1, 3), ('x', 2, 4)]

# [list(itertools.zip_longest(*x[0],fillvalue=x[0][0])) for x in sublist]
BENY
  • 317,841
  • 20
  • 164
  • 234
  • Thanks for the answer. It works for the example. However, what if my input looks like this: `x = [('x', 'y', [1,2], [3,4])]`. I don't think it gives the right output. – Grayrigel Dec 07 '20 at 18:54
  • 1
    @Grayrigel you may need to look at your real data and find the based format to write the special conversion – BENY Dec 07 '20 at 18:57