Question:
I would like to perform a count of the values contained within array1
with the values of the array nomes
, but it is returning an output with the strange values
SCRIPT
array1 = [
'VALUE1',
'VALUE1',
'VALUE2',
'VALUE2',
'VALUE2',
'VALUE3',
'VALUE4',
'VALUE5',
]
nomes = ['VALUE1', 'VALUE2']
for valores in array1:
for linha in nomes:
print(valores.count(linha))
OUTPUT
1 0 1 0 0 1 0 1 0 1 0 0 0 0 0 0
DESIRED OUTPUT
2 3
Answer:
You do not need two for
unless you go tell 'manually' – without using méotodo .count
.
The most correct is to call the .count
method of array1, passing each word you want to count there
array1 = [
'VALUE1',
'VALUE1',
'VALUE2',
'VALUE2',
'VALUE2',
'VALUE3',
'VALUE4',
'VALUE5',
]
nomes = ['VALUE1', 'VALUE2']
for linha in nomes:
print(array1.count(linha))
The way you're doing it, you're counting the occurrence of the word in the "names" list within each word of "array1". (Strings are also strings, so it has the "count" method)
This works, but it's not the best way – since it's going to run through array1 once for each word searched – it won't make any difference for a case with just a few lines, and in a program that runs 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 entire initial list (array1) just once, and counts the values of all the keys it finds. Python has the collections.Counter
class that can do this all 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 ways so far are only if the "names" match is for the entire line of "array1" – if the value in "names" is just a part of the sentence in "array1" you have to create something using two "fors" same – or transferring a "for" to a regular expression)