October 26th, 2013, 02:39 PM
How can i "sniff" nested lists and perform tasks with them?
Assume i have this simple example where
u=[[1,2,3],[4,5,6],7,8,[9,10]] i want to create a code as simple as possible which will recognise which element in u list is a nested list and (for the sake of simplicity of this example) the code returns the sum of all nested lists.I want my code to work on any list not just u eg
u1=[1,14,[2,21],3,4,5,21,[6,7,12],54] etc the position and number of nested lists each time i run the code will be random ,unknown to me who wrote the code.Well,in this example my u list is specific not random...for testing purposes.
my failed code:
for item in kava:
if item==list: #here i have a wrong statement...
u=[[1,2,3],[4,5,6],7,8,[9,10]]#i can make it random if i allow the user
#to decide the contents of u with input() instruction
i am confused....i do not know how to do it in python (version 2.7.5) yet.
October 26th, 2013, 09:24 PM
Along with this method, you have to make your function recursive so that if the inner object is a list, then perform the same operation on them.
>>> l = [[1,2,3],[4,5,6],7,8,[9,10]]
>>> isinstance(l, list)
October 27th, 2013, 05:49 AM
thank you very much.
I knew isinstance() method,how the hell it did not cross my mind to use it.Damn