[英]How to iterate over each position of a character of a string, for a list of strings?
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.我想要做的是遍历列表中字符串的每个 position,以便计算字符“-”出现在每个 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. 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但我想对一个包含超过 100,000 个字符串的文件执行此操作
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提前感谢您的任何回答
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)]
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
变量,每次您的if
子句为真时,他都会添加自己,并且您的列表中将包含'-'
的数量。
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
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.