Flatten a list with sublists and strings [duplicate]

2024/11/16 1:31:38

How can I flatten a list of lists into a list?

For ex,:

Input_List = [['a', 'b'],'c','d',['e', 'f']]

Expectation:

Final_List = ['a','b','c','d','e','f']
Answer

You will need to check the type of each list item to determine if it is merely a value to output or a sublist to expand.

Using a list comprehension:

Input_List = [['a', 'b'],'c','d',['e', 'f']]
Final_List = [v for i in Input_List for v in (i if isinstance(i,list) else [i])]
print(Final_List)
['a', 'b', 'c', 'd', 'e', 'f']

Or using an iterative loop:

Final_List = []
for item in Input_List:if isinstance(item,list): Final_List.extend(item)else:                     Final_List.append(item)
print(Final_List)
['a', 'b', 'c', 'd', 'e', 'f']

Or using a recursive function if you need to flatten all levels of nested lists:

def flat(A):return [v for i in A for v in flat(i)] if isinstance(A,list) else [A]Input_List = [['a', 'b'],'c','d',['e2', 'f3',['x','y']]]
Final_List = flat(Input_List)
print(Final_List)
['a', 'b', 'c', 'd', 'e2', 'f3', 'x', 'y']
https://en.xdnf.cn/q/120383.html

Related Q&A

Guitar string code in Python? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 1…

What is the point of initializing extensions with the flask instance in Flask? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 8 years ago.Improve…

Nested list doesnt work properly

import re def get_number(element):re_number = re.match("(\d+\.?\d*)", element)if re_number:return float(re_number.group(1))else:return 1.0def getvalues(equation):elements = re.findall("…

How can I increment array with loop?

Ive got two lists:listOne = [33.325556, 59.8149016457, 51.1289412359] listTwo = [2.5929778, 1.57945488999, 8.57262235411]I use len to tell me how many items are in my list:itemsInListOne = int(len(list…

Two Complements Python (with as least bits as possible)

I am trying to output the binary representation of an negative number with the least bytes available each time.Example:-3 -> 101 -10 -> 10110

iterating through a column in dataframe and creating a list with name of the column + str

I have a dataframe with 2 coulmn, i want to iterate through the column headers, use that value and add a string to it and use it as the name of a list.rrresampled=pd.DataFrame() resampled[RAT]=dd1[RAT]…

Python multiple inheritance name clashes [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.Questions asking for code must demonstrate a minimal understanding of the problem being solved. Incl…

How to read multiple txt file from a single folder in Python? [duplicate]

This question already has answers here:How to open every file in a folder(8 answers)Closed 3 years ago.How can I read multiple txt file from a single folder in Python?I tried with the following code b…

Time Changing Without Clicking Button

The following code works fine as long as the time in the spinbox does not change. What I want is to do the set the time for a break. The first time it works perfectly but after that if I change the val…

Avoid `logger=logging.getLogger(__name__)` without loosing way to filter logs

I am lazy and want to avoid this line in every python file which uses logging:logger = logging.getLogger(__name__)In january I asked how this could be done, and found an answer: Avoid `logger=logging.g…