Reputation: 477
So I have a list of strings, all of the same length, like this:
list_strings=["a-a--","-ab-b","a---a","b-b-a","aab-a"]
What I want to do it iterate over each position of the strings inside the list, so to calculate the number of times the character "-" appears in each position. In this case for example, position 0 has 1 "-"s, position 1 has 3 "-"s, position 2 has 1 "-"s, position 3 has 5 "-"s. But I want to do this for a file that has more than 100,000 strings
So far I have:
for i in range(0,len(list_strings)):
for j in range(0,len(list_strings[i])):
if list_strings[i][j]=="-":
#count how many "-"s appear in this position and maybe save it in a list?
Thanks in advance for any answer
Upvotes: 2
Views: 836
Reputation: 716
I won't do much explaining, so this is the code to start:
list_strings=["a-a--","-ab-b","a---a","b-b-a","aab-a"]
for string in list_strings:
occurrence = 0
check_letter = '-'
for letter in string:
if letter == check_letter:
occurrence += 1
print('string: ' + string)
print('occurrences: ' + occurrence)
print('\n')
Upvotes: 0
Reputation: 195438
list_strings=["a-a--","-ab-b","a---a","b-b-a","aab-a"]
# if every string in `list_strings` is same length:
out = [v.count('-') for v in zip(*list_strings)]
print(out)
Prints:
[1, 3, 1, 5, 1]
If some strings are different length:
from itertools import zip_longest
out = [v.count('-') for v in zip_longest(*list_strings)]
Upvotes: 3
Reputation: 399
you are good.
just add counter=0
variable who will add himself every time your if
clause is true, and you will have the number of '-'
in your list.
counter =0
for i in range(0,len(list_strings)):
for j in range(0,len(list_strings[i])):
if list_strings[i][j]=="-":
counter = counter +1
Upvotes: 1