Home > other >  Try to find the number of times an item appears in another list (of string)
Try to find the number of times an item appears in another list (of string)

Time:07-18

Have this list and another search list number:

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

how do I make in on python so that it calculates the number of times each str inside number can be found in animal? for example, for 'cat' the answer would be 2 and for dog it would be 1. I tried to use the count method for list, but it works only if I have a str, I need it to search it using the list.

I tried to do a for loop (only for the first index):

found = 0
for char in animal:
    if str(number[0]) in str(animal):
        found = found 1
return found

the problem is that I cannot do that if I have an infinite number of str in number! If I have let's say 10 str in number I would have to do that loop for [0],[1],[2],[3],[4],[5],... which can take a lot of time.

CodePudding user response:

you could try this in simple form

list2 = ['cat', 'cat', 'dog']
number = ['cat', 'dog']


print([list2.count(j) for j in number])

output

[2, 1] #2 is times he find the first value 'cat' inside list2

CodePudding user response:

You may want to try this simple Counter:


from collections import Counter

L =  ['cat', 'cat', 'dog']
to_search = ['cat', 'dog']

counts = Counter(L)       # a dictionary - find item is O(1) 
print(counts)


for item in to_search:
    if item in counts:
        print(item, counts[item])

Output:

cat 2
dog 1

If you're only interested in search one single word/animal, you can just do this:

search_word  = 'cat'
print(counts[search_word])    # 2
  • Related