Page 1 of 1

count occurence in a list of lists in python

Posted: Mon Oct 17, 2016 11:42 am
by pikkip

Syntax: Select all

while i < len(list): 
top = list[i][0]
s = 0
c = 0
while s < len(list):
if top == list[s][0]:
c = c + 1
s = s + 1
count.append(c)
r=r+c



Here I have a list called 'list'

Its contents are:

[['aaa','a','ssssss'], ['ddd','a',ssss']]
I want to count occurenec of each element in the lists.I ran the above code but I got an error saying list out of range.Can anyone solve this??? :frown:

Re: count occurence in a list of lists in python

Posted: Mon Oct 17, 2016 12:03 pm
by L'In20Cible
Please, use:

Code: Select all

[python][/python]


Around your code, this is currently unreadable. That being said, if I understood correctly, you want to get the count of a specific element into all the lists contained into a list? If so, something like the following:

Syntax: Select all

some_list = [['aaa', 'a', 'ssssss'], ['ddd', 'a', 'ssss']]

def get_count(list_, element):
count = 0
for x in list_:
count += x.count(element)
return count

print(get_count(some_list, 'a')) # Will prints 2
There is really no need to use while, and I always tend/recommend to avoid using it unless there is no other alternative.

Re: count occurence in a list of lists in python

Posted: Tue Oct 18, 2016 7:24 am
by pikkip
Thank you