SoFunction
Updated on 2024-11-12

Summary of methods to merge nested lists into one list in python

Method 1: clever use of sum function

Adding the list list to an empty list merges the nested lists into one

a=[[1],[2],[3],[4],[5]]
merge=sum(a,[])
print('sum result:',merge)

Results:

sum result: [1, 2, 3, 4, 5]

Method 2: Chain splicing using the itertools module

() and .from_iterable() functions can splice all the elements of an iterable object and create a new iterator by concatenating the elements. The difference is that the former can be used to splice multiple nested lists, the latter splice a single nested list, the following example.

Use ():

import itertools

a='abc'
b='def'

merge=(a,b)
result = list(merge)

print(' result:',result)

Results:

result: ['a', 'b', 'c', 'd', 'e', 'f']

Use .from_iterable():

import itertools

a=[[1],[2],[3],[4],[5]]
merge=.from_iterable(a)
result = list(merge)

print('.from_iterable result:',result)

Results:

.from_iterable result: [1, 2, 3, 4, 5]

Method 3: Iterative judgment conditions

Iterates over each element within the list, adding it to the generator if the element is not a list or tuple, and continuing the recursive call if it's an iterable object until all the sublists are broken up, eventually returning a large list.

def flat(l):
    for k in l:
        if not isinstance(k, (list, tuple)):
            yield k
        else:
            yield from flat(k)
a=[[1],[2],[3],[4],[5]]
print ('flat result:',list(flat(a)))

Results:

flat result: [1, 2, 3, 4, 5]

Method 4: Simple and crude string substitution

Directly convert the entire list to a string, then replace the borders, and finally convert back to list format via the eval function

a=[[1],[2],[3],[4],[5],[['m'],['n']]]
result = eval('[%s]'%repr(a).replace('[', '').replace(']', ''))
print('eval result:',result)

Results:

eval result: [1, 2, 3, 4, 5, 'm', 'n']

An additional interesting interview question

list_info = [1,2,3,4,5]
print(list_info[10:])

What will be output? Why?

1) Causes IndexError

2) Output [1,2,3,4,5]

3) Compilation errors

4) Output []

summarize

to this article on the python nested list merged into a list of articles on this, more related python nested list merged into a list of content, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!