Smooth multidimensional array in python 3

I have a list of numbers: testList = [1, [1], [12], 2, 3]

I want this to become: flatList = [1, 1, 12, 2, 3]

Using a typical list comprehension, for example below, does not work.

flatList = [val for sublist in testList for val in sublist]
TypeError: 'int' object is not iterable

I suspected this was due to the fact that non-nested elements are treated as exterminated sublists, so I tried this:

flatList = [val if isinstance(sublist, int) == False else val for sublist in testlist for val in sublist]

But I do not understand the syntax, or if there is a better way to do this. Trying to remove val from an else condition means val undefined. Like everything, it still gives me the same TypeError.

The code below works for me, but I'm curious to know if this can be done in the style of understanding lists and people's opinions on this matter.

for sublist in testlist:
    if type(sublist) == int:
        flat.append(sublist)
    else:
        for val in sublist:
            flat.append(val)
print(flat)

>>>[1, 1, 12, 2, 3]
+4
source share
2 answers

Python 3, yield from . Python 3.3.

, , :

test_list = [1, [1], [12, 'test', set([3, 4, 5])], 2, 3, ('hello', 'world'), [range(3)]]

def flatten(something):
    if isinstance(something, (list, tuple, set, range)):
        for sub in something:
            yield from flatten(sub)
    else:
        yield something


print(list(flatten(test_list)))
# [1, 1, 12, 'test', 3, 4, 5, 2, 3, 'hello', 'world', 0, 1, 2]
print(list(flatten('Not a list')))
# ['Not a list']
print(list(flatten(range(10))))
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

:

def flatten(something, level=0):
    print("%sCalling flatten with %r" % ('  ' * level, something))
    if isinstance(something, (list, tuple, set, range)):
        for sub in something:
            yield from flatten(sub, level+1)
    else:
        yield something

list(flatten([1, [2, 3], 4]))
#Calling flatten with [1, [2, 3], 4]
#  Calling flatten with 1
#  Calling flatten with [2, 3]
#    Calling flatten with 2
#    Calling flatten with 3
#  Calling flatten with 4
+2

,

flatList = [item[0] if isinstance(item, list) else item for item in testList]
+1

Source: https://habr.com/ru/post/1689686/


All Articles