Home > other >  occurrence of specific character in multiple strings
occurrence of specific character in multiple strings

Time:08-24

The multiple strings that needed to be searched are stored in a file values.txt (the Input File) which for example contains information as follows:

XXVVXXVVVVVXXVXVV
VXVXVXXXXXVVVVXXX
VVVVXXVVVXVVXXXXX
XVXXXVVVXXVXXVXVX
VXXVVXVXXVVVXXVVX
XVXVXXXXXXXXVVVVV
VVVXXVVXVXVVXXVVX
XVXXVXXXVVXXXVXXX
VVVVXXXXXXVXVXXXX
VXVVXVVXVVXVVVVXV
VVXVXVXXVVXXVVXVV
VVXVVXXVVXXXVVVXV
XVXVVVVXVXVVVVVVV
VXXVVXVXVXVVXXXVX
XVVVVXVXVXXXXVVVX
VXXVVVVXXVXVXVVVX

I'm trying to count the occurrence of V in every line for index[x], x being the position of a character in every line.

For example, there are 10 "V" in every first character of the lines. 10 "V" in the second character of the lines and 7 "V" in the third character of the lines.

I have already tried enlisting the lines en counting the amount of "V" in every line, but i'm not getting anyware. Any suggestions?

expected answer: [10, 10, 7, 12, 8, 6, 10, 4, 10, 6, 9, 8, 7, 11, 8, 10, 6]

CodePudding user response:

I would use a list comprehension with zip and a Counter:

from collections import Counter

out = [Counter(col)['V'] for col in zip(*text.split('\n'))]

Alternative without import:

out = [len([c for c in col if c == 'V']) for col in zip(*text.split('\n'))]

output: [10, 10, 7, 12, 8, 6, 10, 4, 10, 6, 9, 8, 7, 11, 8, 10, 6]

used input:

text = '''XXVVXXVVVVVXXVXVV
VXVXVXXXXXVVVVXXX
VVVVXXVVVXVVXXXXX
XVXXXVVVXXVXXVXVX
VXXVVXVXXVVVXXVVX
XVXVXXXXXXXXVVVVV
VVVXXVVXVXVVXXVVX
XVXXVXXXVVXXXVXXX
VVVVXXXXXXVXVXXXX
VXVVXVVXVVXVVVVXV
VVXVXVXXVVXXVVXVV
VVXVVXXVVXXXVVVXV
XVXVVVVXVXVVVVVVV
VXXVVXVXVXVVXXXVX
XVVVVXVXVXXXXVVVX
VXXVVVVXXVXVXVVVX'''
  • Related