0

How to convert a 2 element(with x elements) array into a 2*x elelment array?

Using the below example => How do I convertbbb in to bbb2

>>> bbb
[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]
>>> bbb2
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
>>> len(bbb)
2
>>> len(bbb2)
4

I am thinking of a for loop and looping through until I get what I want but is there a better way?

possibly related:
How do I concatenate two lists in Python?
How to make a flat list out of list of lists

HattrickNZ
  • 4,373
  • 15
  • 54
  • 98
  • 1
    The [second answer](https://stackoverflow.com/a/953097/5648954) in the second link you provided gives what you're after – Nick Parsons Oct 07 '19 at 01:01

3 Answers3

1

Something like

bbb2 = sum(bbb, [])

is one way, by (ab)using the fact that sum only cares if addition is supported (which for lists is concatenation). But it will very likely "lose" to a proper list comprehension performance (and maybe clarity) wise, for example:

bbb2 = [xi for xo in bbb for xi in xo]

"Loop" variables xi, xo should be renamed to taste.

jedwards
  • 29,432
  • 3
  • 65
  • 92
  • Your first idea is faster :) import timeit timer = timeit.timeit('[i for bi in bbb for i in bi]', 'bbb=[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]') print(timer) # 0.209 secs timer = timeit.timeit('sum(bbb, [])', 'bbb=[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]') print(timer) # 0.165 secs – jmbarbier Oct 07 '19 at 01:07
  • @jmbarbier Thanks for testing that! I'm surprised because I would have assumed it would create each of the intermediary lists just to be thrown out after the following step. I'll have to do some digging to find if there's something special going on. – jedwards Oct 07 '19 at 01:11
0

You could do it with list comprehension:

>>> bbb2 = [item for sublist in bbb for item in sublist]
>>> bbb2
>>> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

It may be possible with numpy but I'm not sure.

Rhys
  • 3
  • 1
0

This will not be better performance wise for your example array. But if your incoming lists are of arbitrary dimension N*M then you can create a generic recursive function.

Code sample:

bbb = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]

def generic_recursive(thelist, res):
    """
    Generic Recursive Function
    Converting Array of Dim = n arrays to dim 2
    """
    if not thelist:
        return res
    else:
        if isinstance(thelist[0], int):
            res.append(thelist)
            return generic_recursive([], res)
        else:
            res.extend( generic_recursive(thelist[0], []))
            return  generic_recursive(thelist[1:], res)

bbb2 = generic_recursive(bbb,[])
print(bbb)
print(bbb2)
print(len(bbb))
print(len(bbb2))
Grebtsew
  • 192
  • 5
  • 13