How to make a flat list from nested lists? [duplicate]

2024/7/7 6:00:14

Given a nested list of integers, implement an iterator to flatten it. Each element is either an integer, or a list -- whose elements may also be integers or other lists. For example, if the input is [[1,1],2,[1,1]], then the output is [1, 1, 2, 1, 1]. If the input is [1,[4,[6]]], then the output is [1, 4, 6].

Would anyone be able to advise me as to where the code below went wrong? I am just starting out with python.

def eb34(list1):flat_list = []for i in range(len(list1)):if type(list[i]) == list:flat_list += flatten(list1[i])else:flat_list.append(list1[i])return flat_list
Answer

You can use recursion:

def flatten(arg):if not isinstance(arg, list): # if not listreturn [arg]return [x for sub in arg for x in flatten(sub)] # recurse and collectprint(flatten([[1,1],2,[1,1]])) # [1, 1, 2, 1, 1]
print(flatten([1,[4,[6]]]))     # [1, 4, 6]

Or to make a generator,

def flatten(arg):if not isinstance(arg, list): # if not listyield argelse:for sub in arg:yield from flatten(sub)print(*flatten([[1,1],2,[1,1]])) # 1 1 2 1 1
print(*flatten([1,[4,[6]]]))     # 1 4 6
https://en.xdnf.cn/q/119876.html

Related Q&A

Python 2.7: import performance

currently, I am importing bunch of .py files scattered across the file system via: def do_import(name):import impfp, pathname, description = imp.find_module(name)with fp:return imp.load_module(name, fp…

change first line of a file using bash

I need to change a single line in a file. It is always in the first line of the file. It looks like:h\tn0 n1 n2 n3 n4 n5 n6 n7 n8 n9 hilu cjt 1 1000000there is a tab in all gaps except …

1 to 2 matching in two dataframes with different sizes in Python/R

please help me with this problem Ive been struggling all day lol, solution in either Python or R is fine! Please help Im really stuck!!! I have two dataframes - df1 has 44 rows, df2 has 100 rows, they …

Can someone fix this? pip install intents

Im not sure why this is failing but I need help to fix it please Ive been trying to fix it for about 2 hours now and cant figure it out. I have tried to restart my computer, look it up on google etc. b…

Calculating Average Performance Measures in M/M/1 System Using SimPy

I am seeking to calculate the average waiting times, and average service times in the following M/M/1 queueing system, but I am not able to calculate the averages. It writes down to the console each cu…

Python: Whats the difference between import X and from X import *? [duplicate]

This question already has answers here:Use import module or from module import?(23 answers)Closed 7 years ago.I use to think both are equal until I tried this:$python Python 2.7.13 (default, Dec 17 20…

Python iterate through pixels of image

Im trying to iterate through pixels of an image. I set the size and then use a for loop, however I get a type error: object not iterable. I have imported PIL and Imagew=100 h=200 im=im.resize((w,h), Im…

Geocoding with Geopy and big data

I have this CSV file which im feeding with this python scriptimport csv from geopy.geocoders import OpenCagegeolocator = OpenCage() #here some parameters are needed with open(/Users/Ian/Desktop/Test02/…

an error in sending json data to flask server [duplicate]

This question already has answers here:How to get POSTed JSON in Flask?(13 answers)Closed 1 year ago.I have a json data as {"age":59.0,"bp":70.0,"sg":1.01,"al":…

terminate a python program when it hanged using subprocess python

I have a main.py which open a new cmd (subprocess) when another program (test.py, in same directory) is hanged. To determining test.py is hanged or not, I used latest modified time (os.path.getmtime(te…