Clean nested lists in Python -
Clean nested lists in Python -
say have list in python:
l = [1, 2, 3, [a, [[9, 10, 11]], c, d], 5, [e, f, [6, 7, [8]]]]
i clean nested lists that, if of length 1 (just 1 item), "pulled up" out of list, such revised list like:
l = [1, 2, 3, [a, [9, 10, 11], c, d], 5, [e, f, [6, 7, 8]]]
naturally can check if len == 1
, replace index contents, but... there built-in way this?
you utilize recursive function:
def expand_singles(item): if isinstance(item, list): if len(item) == 1: homecoming expand_singles(item[0]) homecoming [expand_singles(i) in item] homecoming item
demo:
>>> def expand_singles(item): ... if isinstance(item, list): ... if len(item) == 1: ... homecoming expand_singles(item[0]) ... homecoming [expand_singles(i) in item] ... homecoming item ... >>> l = [1, 2, 3, ['a', [[9, 10, 11]], 'c', 'd'], 5, ['e', 'f', [6, 7, [8]]]] >>> expand_singles(l) [1, 2, 3, ['a', [9, 10, 11], 'c', 'd'], 5, ['e', 'f', [6, 7, 8]]]
python list data-cleansing
Comments
Post a Comment