list of lists to single list python
flat_list = [item for sublist in t for item in sublist]
list of lists to single list python
flat_list = [item for sublist in t for item in sublist]
python convert nested list to list of strings
# Basix syntax:
['delim'.join([str(elem) for elem in sublist]) for sublist in my_list]
# Where delim is the delimiter that will separate the elements of the
# nested lists when they are flattened to a list of strings
# Note, this uses two "levels" of list comprehension
# Example usage 1:
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'] # List of space-delimited strings
# Example usage 2:
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'] # List of underscore-delimited strings
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]
how to make one list from nested list
>>> from collections import Iterable
def flatten(lis):
for item in lis:
if isinstance(item, Iterable) and not isinstance(item, str):
for x in flatten(item):
yield x
else:
yield item
>>> lis = [1,[2,2,2],4]
>>> list(flatten(lis))
[1, 2, 2, 2, 4]
>>> list(flatten([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
python nested list
L = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
for list in L:
for number in list:
print(number, end=' ')
# Prints 1 2 3 4 5 6 7 8 9
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us