user3398505
user3398505

Reputation: 607

Counting integer in a nested list

Say I have a list [1, [2, 1], 1, [3, [1, 3]], [4, [1], 5], [1], 1, [[1]]] And I want to count the number of 1's in the list. How do i do that with .count ?? Is there anyway to remove [] like enumerate(seq) which removes () then count the number of 1's in the list?

Upvotes: 1

Views: 97

Answers (2)

santosh-patil
santosh-patil

Reputation: 1550

This might not be the coolest way, but it works:

l=[1, [2, 1], 1, [3, [1, 3]], [4, [1], 5], [1], 1, [[1]]]
>>> from compiler.ast import flatten
>>> flatten(l).count(1)
8

Here, as name suggests, flatten() converts the nested list into simple single level list. And counting the number of 1s from resulting list achieves the task.

Upvotes: 4

Reite
Reite

Reputation: 1667

You need a function to traverse an arbitrarily nested list. Then the counting is trivial. The traversing can be accomplished with a recursive generator:

def traverse(val):
    if isinstance(val, list):
        for v in val:
            for x in traverse(v):
                yield x 
    else:
        yield val


>>> list(traverse([1, [2, 1], 1, [3, [1, 3]], [4, [1], 5], [1], 1, [[1]]]))
[1, 2, 1, 1, 3, 1, 3, 4, 1, 5, 1, 1, 1]

This definition would be even nicer with the new yield from syntax in python 3.3, with it we could replace one of the loops:

def traverse(val):
    if isinstance(val, list):
        for v in val:
            yield from traverse(v)
    else:
        yield val

Upvotes: 2

Related Questions