Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested List and count()

Tags:

python

list

I want to get the number of times x appears in the nested list.

if the list is:

list = [1, 2, 1, 1, 4]
list.count(1)
>>3

This is OK. But if the list is:

list = [[1, 2, 3],[1, 1, 1]]

How can I get the number of times 1 appears? In this case, 4.

like image 629
Yugo Kamo Avatar asked Apr 29 '11 05:04

Yugo Kamo


7 Answers

>>> L = [[1, 2, 3], [1, 1, 1]]
>>> sum(x.count(1) for x in L)
4
like image 141
Thomas Edleson Avatar answered Oct 11 '22 13:10

Thomas Edleson


itertools and collections modules got just the stuff you need (flatten the nested lists with itertools.chain and count with collections.Counter

import itertools, collections

data = [[1,2,3],[1,1,1]]
counter = collections.Counter(itertools.chain(*data))
print counter[1]

Use a recursive flatten function instead of itertools.chain to flatten nested lists of arbitrarily level depth

import operator, collections

def flatten(lst):
    return reduce(operator.iadd, (flatten(i) if isinstance(i, collections.Sequence) else [i] for i in lst))

reduce with operator.iadd has been used instead of sum so that the flattened is built only once and updated in-place

like image 39
Imran Avatar answered Oct 11 '22 13:10

Imran


Here is yet another approach to flatten a nested sequence. Once the sequence is flattened it is an easy check to find count of items.

def flatten(seq, container=None):
    if container is None:
        container = []

    for s in seq:
        try:
            iter(s)  # check if it's iterable
        except TypeError:
            container.append(s)
        else:
            flatten(s, container)

    return container


c = flatten([(1,2),(3,4),(5,[6,7,['a','b']]),['c','d',('e',['f','g','h'])]])
print(c)
print(c.count('g'))

d = flatten([[[1,(1,),((1,(1,))), [1,[1,[1,[1]]]], 1, [1, [1, (1,)]]]]])
print(d)
print(d.count(1))

The above code prints:

[1, 2, 3, 4, 5, 6, 7, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
1
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
12
like image 32
sateesh Avatar answered Oct 11 '22 12:10

sateesh


Try this:

reduce(lambda x,y: x+y,list,[]).count(1)

Basically, you start with an empty list [] and add each element of the list list to it. In this case the elements are lists themselves and you get a flattened list.

PS: Just got downvoted for a similar answer in another question!

PPS: Just got downvoted for this solution as well!

like image 28
manojlds Avatar answered Oct 11 '22 13:10

manojlds


If there is only one level of nesting flattening can be done with this list comprenension:

>>> L = [[1,2,3],[1,1,1]]
>>> [ item for sublist in L for item in sublist ].count(1)
4
>>> 
like image 30
dting Avatar answered Oct 11 '22 12:10

dting


For the heck of it: count to any arbitrary nesting depth, handling tuples, lists and arguments:

hits = lambda num, *n: ((1 if e == num else 0)
    for a in n
        for e in (hits(num, *a) if isinstance(a, (tuple, list)) else (a,)))

lst = [[[1,(1,),((1,(1,))), [1,[1,[1,[1]]]], 1, [1, [1, (1,)]]]]]
print sum(hits(1, lst, 1, 1, 1))

15
like image 23
samplebias Avatar answered Oct 11 '22 14:10

samplebias


def nested_count(lst, x):
    return lst.count(x) + sum(
        nested_count(l,x) for l in lst if isinstance(l,list))

This function returns the number of occurrences, plus the recursive nested count in all contained sub-lists.

>>> data = [[1,2,3],[1,1,[1,1]]]
>>> print nested_count(data, 1)
5
like image 21
shang Avatar answered Oct 11 '22 12:10

shang