1

This is a sample of the array I am dealing with:

    records = [[[['   1'], ['   2'], ['   3'], ['   4']]], [[['   red'], ['   blue'], ['   black'], ['   white']]]]

I want to end up with a structure like this one:

    [['   1','   2','   3','   4'],['   red','   blue','   black','   white']]

I've tried the following:

    levelOne = [recs for sublist in records for recs in sublist]
    final = [recs for sublist in levelOne for recs in sublist]

And what I've got was:

    [['   1'], ['   2'], ['   3'], ['   4'], ['   red'], ['  blue'], ['   black'], ['   white']]

3 Answers 3

1

Use the built-in itertools.chain.from_iterable for flattening/chaining. Then it's just a matter of applying to the right nested list level:

import itertools
list(list(itertools.chain.from_iterable(rec[0])) for rec in records)

[['   1', '   2', '   3', '   4'],
 ['   red', '   blue', '   black', '   white']]

Or as a single list comprehension

[[r[0] for r in rec[0]] for rec in records]

[['   1', '   2', '   3', '   4'],
 ['   red', '   blue', '   black', '   white']]

Or if your nested list is a numpy array to begin with, you can use numpy.reshape:

np.reshape(np.array(records), (2, 4))

array([['   1', '   2', '   3', '   4'],
       ['   red', '   blue', '   black', '   white']], dtype='<U8')
Sign up to request clarification or add additional context in comments.

Comments

1

If your records array is numpy array then remove np.array(records) just put records If you want simple list then remove np.array casting in np.array(list(...)) in res

import numpy as np
res=np.array(list(map(lambda x : x.reshape(-1), np.array(records))))

Comments

1

You can use the method reshape:

records = np.array(records)
records = records.reshape(2, -1)

print(records)

Output:

array([['   1', '   2', '   3', '   4'],
       ['   red', '   blue', '   black', '   white']], dtype='<U8')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.