how to count the number of a certain character in a list of list of string in python version 3?

Question:

input:

animals= [['dog', 'snake', 'snake'], ['dog', 'dog', 'cat'], ['snake', 'snake', 'cat']]

    animal_to_count = ['dog', 'cat']

output:

animal_found = [3, 2]

I have a list of list of strings. I want to count the number of each animals in that list of list of string.

I tried to do this with a for loop to target them individually:

def find_animals(animals: List[List]str, animals_to_count: List[str]) -> List[int]

counts = [0, 0]
    for char in animals:
       for s in char:
           if s in animal_to_count:
               counts=counts+1
               return counts

Now this is the part where I am bugging, I know I am supposed to use counts so that every time the loops goes by, it add it to the count, but the problem is I don’t know how to do it. When I do what is above, I get an error. This is for an assignment, and I would like to find the answer without using any built-in function (beside all of the list method, string method).

Asked By: Family Sultani

||

Answers:

This will return dictionary containing counts for each animal in the list.

def find_animals(animals:List[List], animals_to_count: List[str]):
  d = {}
  for animal in animals_to_count:
    d[animal] = 0

  for char in animals:
    for s in char:
        if s in animals_to_count:
          d[s] += 1

  return d

res = find_animals(animals,animals_to_count)
print('Dogs:',res['dog'],' ','Cats:',res['cat'])
Answered By: Abhishek Kumar

this should work:

animals= [['dog', 'snake', 'snake'], ['dog', 'dog', 'cat'], ['snake', 'snake', 'cat']]
animal_to_count = ['dog', 'cat']

results = []
for sublist in animals:
    results_per_animal_count = []
    for count_animal in animal_to_count:
        counter = 0
        for animal in sublist:
            if animal == count_animal:
                counter += 1
        results_per_animal_count.append(counter)
    results.append(results_per_animal_count)

The printout of results is

[[1, 0], [2, 1], [0, 1]]

EDIT

If you want to get the aggregated list you can use:

animals= [['dog', 'snake', 'snake'], ['dog', 'dog', 'cat'], ['snake', 'snake', 'cat']]
animal_to_count = ['dog', 'cat']

results = []

for count_animal in animal_to_count:
    counter = 0
    for sublist in animals:
        for animal in sublist:
            if animal == count_animal:
                counter += 1
    results.append(counter)

Where the print out of results is:

[3, 2]

EDIT 2

animals= [['dog', 'snake', 'snake'], ['dog', 'dog', 'cat'], ['snake', 'snake', 'cat']]
animal_to_count = ['snake'] # here you add and remove search items

results = []

for count_animal in animal_to_count:
    counter = 0
    for sublist in animals:
        for animal in sublist:
            if animal == count_animal:
                counter += 1
    results.append(counter)

printout

[4]
Answered By: Pieter Geelen

You should count "dog" and "cat" separately. Something like this:

def find_animals(animals, animals_to_count):
    counts = [0]*len(animals_to_count)
    for items in animals:
        for item in items:
            for index, animal_to_count in enumerate(animals_to_count):
                if item==animal_to_count:
                    counts[index]+=1
    return counts

[0]*len(animals_to_count) creates a list with as many zeros as there are elements in animals_to_count

Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.