#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    14
    Rep Power
    0

    How can i "sniff" nested lists and perform tasks with them?


    objective:
    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:
    Code:
    def mylistsum(kava):
        result=0
        for item in kava:
            if item==list: #here i have a wrong statement...
                z=sum(item)
                result+=z
        return result
    
    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
    print 'u=',u
    print mylistsum(u)
    problem:
    i am confused....i do not know how to do it in python (version 2.7.5) yet.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Location
    /dev/null
    Posts
    163
    Rep Power
    19
    Code:
    >>> l = [[1,2,3],[4,5,6],7,8,[9,10]]
    >>> isinstance(l[0], list)
    True
    >>>
    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.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    14
    Rep Power
    0
    thank you very much.
    I knew isinstance() method,how the hell it did not cross my mind to use it.Damn

IMN logo majestic logo threadwatch logo seochat tools logo