nested list into one list python code example
Example 1: python convert nested list to list of strings
['delim'.join([str(elem) for elem in sublist]) for sublist in my_list]
my_list = [[1, '1', 1], [2,'2',2], [3,'3',3]]
[' '.join([str(elem) for elem in sublist]) for sublist in my_list]
--> ['1 1 1', '2 2 2', '3 3 3']
my_list = [[1, '1', 1], [2,'2',2], [3,'3',3]]
['_'.join([str(elem) for elem in sublist]) for sublist in my_list]
--> ['1_1_1', '2_2_2', '3_3_3']
Example 2: convert 2 level nested list to one level list in python
>>> from collections import Iterable
>>> def flat(lst):
... for parent in lst:
... if not isinstance(i, Iterable):
... yield parent
... else:
... for child in flat(parent):
... yield child
...
>>> list(flat(([1,[2,2,2],4]))
[1, 2, 2, 2, 4]
Example 3: python nested list
my_list = [[1, 2], ["one", "two"]]
my_list[1][0]