i want number of times x appears in nested list.
if list is:
list = [1, 2, 1, 1, 4] list.count(1) >>3
this ok. if list is:
list = [[1, 2, 3],[1, 1, 1]]
how can number of times 1 appears? in case, 4.
here yet approach flatten nested sequence. once sequence flattened easy check find count of items.
def flatten(seq,container=none): if container none: container = [] s in seq: if hasattr(s,'__iter__'): flatten(s,container) else: container.append(s) 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
Comments
Post a Comment