0

I'm aware of how completely flattening a list of sublists is done, however, I am unsure of how to do so by only one level.

For example, a sublist like [[[1, 2], 3], [[4, 5], 6], [[7, 8], 9]] would get flattened into [1, 2, 3, 4, 5, 6, 7, 8, 9].

However, I'm struggling to figure out a way for the result to be [[1, 2, 3], [4, 5, 6], [7, 8, 9]], without ending up flattening the entire list.

Any help will be appreciated!

Jim Lee
  • 11
  • Welcome to SO! The link shows how to flatten a list one level. Since you want each inner list flattened, wrap it in another loop. Since ints are also in there, you'll also need to pass those to the output without flattening. – ggorlen Nov 03 '20 at 06:09
  • Hello, thank you, I'm brand new to CS and the learning curve is quite steep....anyways, yes, that does answer my question, never would of thought of that, thank you so much! – Jim Lee Nov 03 '20 at 06:19
  • I gotcha. Glad the link helps. One solution might be `[list(chain(*[y if isinstance(y, list) else [y] for y in x])) for x in your_list]`. Use `from itertools import chain` for this. – ggorlen Nov 03 '20 at 06:29

1 Answers1

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

result_array = []

def flat_element(el):

    global result_array

    _class = ''
    try:
        _class = str(type(el)).split("'")[1]
    except:
        pass

    if _class in ('list', 'tuple'):
        for elem in el:
            flat_element(elem)
    else:
        result_array.append(el)

flat_element(input_array)

print(result_array)

main_array = []

for sub_array in input_array:
    result_array = []
    flat_element(sub_array)
    main_array.append(result_array)

print(main_array)

example_array = [[[1, 2], 3], [[4, 5], 6], [[7, 8], 9]]
main_array = []

for sub_array in example_array:
    result_array = []
    flat_element(sub_array)
    main_array.append(result_array)

print(main_array)

Output:

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

Working with arrays and tuples

rzlvmp
  • 7,512
  • 5
  • 16
  • 45