-4

If I have

animal = [['cat', 'cat', 'dog'], ['cat', 'cat', 'dog'], ['cat', 'cat', 'dog']] 

and

item_to_find = ['cat', 'dog']

how do I calculate the number of times each string inside item_to_find can be found in animal? for example, for 'cat', the answer would be 6, and for 'dog' it would be 3. I need to do this without using collectiouns.Counter or a dictionary. I tried to use count, but it only works if it's a list of strings, and not a list of list of strings.

I tried to do it this way:

for i in item_to_find:
    print(animal.count(i))

but like I was saying this only works for a list of strings and not a list of list of strings.

My result would look like something like this: [6, 3] (as a list).

CrazyChucky
  • 3,263
  • 4
  • 11
  • 25
kfnwtfn
  • 1
  • 2
  • What do you mean "without a counter or dictionary"? Do you mean you're not allowed to use `dict` or anything imported from standard libraries like `collections.Counter`? Can you share what code you've written so far, and explain in more detail where you're stuck? – Grismar Jul 18 '22 at 02:57
  • yes thats what i mean! and yes I will edit that just a minute please. – kfnwtfn Jul 18 '22 at 02:58
  • 1
    You'd also want to explain in what form the results would need to be collected or written to the screen, since a dictionary would actually make a lot of sense as a data structure here, but apparently you're barred from using it. – Grismar Jul 18 '22 at 02:59
  • Depending on your use case, and what else you may or may not be doing to the data, you may want to simply [flatten the list](https://stackoverflow.com/questions/952914/how-do-i-make-a-flat-list-out-of-a-list-of-lists). Whether or not it's a duplicate (this question was closed and reopened), it's probably handy to know about. – CrazyChucky Jul 18 '22 at 03:14

2 Answers2

1

Use sum along with count to sum up the counts in all the sub-lists:

>>> animal = [['cat', 'cat', 'dog'], ['cat', 'cat', 'dog'], ['cat', 'cat', 'dog']]
>>> item_to_find = ['cat', 'dog']
>>> [(item, sum(a.count(item) for a in animal)) for item in item_to_find]
[('cat', 6), ('dog', 3)]

If you wanted to avoid using count you can do it almost as easily by using a nested generator with sum:

>>> [(item, sum(i == item for a in animal for i in a)) for item in item_to_find]
[('cat', 6), ('dog', 3)]

If you don't want to know which item each count goes with, make it a list of just the counts instead of a tuple that includes the item:

>>> [sum(a.count(item) for a in animal) for item in item_to_find]
[6, 3]
Samwise
  • 68,105
  • 3
  • 30
  • 44
1

You can use iteration:

occurrences = [0] * len(item_to_find)
for sublist in animal:
    for idx, item in enumerate(item_to_find):
        occurrences[idx] += sublist.count(item)

Now occurrences will be [6, 3] for the example given.

linger1109
  • 500
  • 2
  • 11