count occurence in a list of lists in python

All other Source.Python topics and issues.
User avatar
pikkip
Junior Member
Posts: 7
Joined: Mon Oct 17, 2016 11:38 am

count occurence in a list of lists in python

Postby pikkip » Mon Oct 17, 2016 11:42 am

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:
Last edited by Ayuto on Mon Oct 17, 2016 12:25 pm, edited 1 time in total.
Reason: Added Python code tags
User avatar
L'In20Cible
Project Leader
Posts: 927
Joined: Sat Jul 14, 2012 9:29 pm
Location: Québec

Re: count occurence in a list of lists in python

Postby L'In20Cible » Mon Oct 17, 2016 12:03 pm

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.
User avatar
pikkip
Junior Member
Posts: 7
Joined: Mon Oct 17, 2016 11:38 am

Re: count occurence in a list of lists in python

Postby pikkip » Tue Oct 18, 2016 7:24 am

Thank you

Return to “General Discussion”

Who is online

Users browsing this forum: No registered users and 1 guest