You don’t need two for
unless you are going to count 'manually' - without using the menu .count
.
The correct thing is to call the method .count
of array1, passing each word you want to tell there
array1 = [
'VALUE1',
'VALUE1',
'VALUE2',
'VALUE2',
'VALUE2',
'VALUE3',
'VALUE4',
'VALUE5',
]
nomes = ['VALUE1', 'VALUE2']
for linha in nomes:
print(array1.count(linha))
The way you are doing, is provided the occurrence of the word on the list "names" within every word of "array1". (Strings are also sequences, so it has the "Count" method")
This works, but it is not the best way - since it will go through array1 once for each searched word - it will not make any difference to a case with only a few lines, and in a program that runs only once - the time must be less than 10 milliseconds. But if this happens in a web application where response time is critical, it can start to make a difference.
The ideal is an algorithm that goes through the initial list (array1) only once, and already count the values of all the keys you find. Python has the class collections.Counter
that can do this at once - but to better understand the algorithm:
array1 = ...
nomes = {'VALUE1': 0, 'VALUE2': 0}
for frase in array1:
if frase in nomes:
nomes[frase] += 1
print(nomes)
(The two forms so far are only if the match of "names" is for the entire line of "array1" - if the value in "names" is only a part of the sentence in "array1" you have to create something using two "for" even - or by transferring a "for" to a regular Express)
It’s only now that I realize I’ve been given negative for no reason....
– JeanExtreme002