I made a list with some character in it and I looped through it to calculate the number of a specific character and it returns the number of all the characters inside the list and not the one's that I said it to. Take a look at my code and if someone can help I will appreciate it!
This is the code:
array = ['a', 'b', 'c', 'a']
sum_of_as = 0
for i in array:
if str('a') in array:
sum_of_as = 1
print(f'''The number of a's in this array are {sum_of_as}''')
CodePudding user response:
The most pythonic method would be to use sum() generator.
list_of_strings = ["a", "b,", "c", "d", "a"]
count = sum(string.count("a") for string in list_of_strings)
print(count)
>>> 2
The above iterates each element of the the list and totals up (sums) the amount of times the letter "a" is found, using str.count()
str.count()
is a method that returns the number of how many times the string you supply is found in that string you call the method on.
name = "david"
print(name.count("d"))
>>> 2
This is the equivalent of doing
count = 0
list_of_strings = ["a", "b,", "c", "d", "a"]
for string in list_of_strings:
count = string.count("b")
print(count)
If you know the list is only ever going to contain single letter strings, as per your example, or if you are searching for a word in a list of words, then you can simply use list_of_strings.count("my_string")
.
Be aware though that will not count things such us
l = ["ba", "a", "c"]
where the response would be 1 as opposed to 2. The top examples do account for this, so it really does depend on your data and use case.
CodePudding user response:
The if str('a') in array
evaluates to True
in every for-loop iteration, because there is 'a'
in the array
.
Try to change the code to if i == "a":
array = ["a", "b", "c", "a"]
sum_of_as = 0
for i in array:
if i == "a":
sum_of_as = 1
print(sum_of_as)
Prints:
2
OR:
Use list.count
:
print(array.count("a"))