Answers for "turn nested list into list"

2

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
Posted by: Guest on October-04-2020
0

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]
Posted by: Guest on September-02-2020
0

Nested list into flat list python

def flatten_list(_2d_list):
    flat_list = []
    # Iterate through the outer list
    for element in _2d_list:
        if type(element) is list:
            # If the element is of type list, iterate through the sublist
            for item in element:
                flat_list.append(item)
        else:
            flat_list.append(element)
    return flat_list

nested_list = [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
print('Original List', nested_list)
print('Transformed Flat List', flatten_list(nested_list))
Posted by: Guest on October-01-2021

Python Answers by Framework

Browse Popular Code Answers by Language