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

Time:07-28

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).

CodePudding user response:

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

CodePudding user response:

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]

CodePudding user response:

This is what you want?

def find_animals(animals:List[List], animals_to_count: List[str]):
  counts = 0
  for char in animals:
    for s in char:
        if s in animal_to_count:
            counts  = 1
  return counts
  • Related