backend/python

python: make flat list

seul chan 2018. 6. 22. 19:25

usling list comprehension & lambda

# list comprehension
flat_list = [item for sublist in l for item in sublist]
# labmda
flatten = lambda l: [item for sublist in l for item in sublist]

using itertools.chain()

import itertools
flat_list = list(itertools.chain.from_iterable(l))

using sum

super easy but not inefficient way

flat_list = sum(l, [])

using reduce

from functools import reduce
flat_list = reduce(lambda x, y: x + y, l)

# or using operator
import operator
flat_list = reduce(operator.concat, l)

cons

  • can use only one-depth list
  • can use only list that have list (not in flat list)

For solving that cons, you can make your own def like _flat

from collections import Iterable

def _flat(items):
    for x in items:
        if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
            yield from _flat(x)
        else:
            yield x

flat_list = list(_flat(l))


'backend > python' 카테고리의 다른 글

python: make variable from dict  (0) 2018.07.25
python: pyenv, virtualenv, auto in mac os  (0) 2018.06.28
python: make uuid in python  (0) 2018.06.04
python: use python like npm - pipenv  (0) 2018.05.25
python: check if variable exists in python  (0) 2018.05.11