HighwayJohn HighwayJohn - 1 month ago 13
Python Question

How many specific characters in a list

I have the following problem. In my code I am getting at one point a list which does look like the following example:

['-0---110', '--1--110', '01---100', '1--101-0', '10-1-100',...., '10100010']


Now I want to know how often does a string occur with 0, 1, 2, 3,... bars.
Is there an easy way to do it?

Edit: I thought something like
['-0---110', '--1--110', '01---100', '1--101-0', '10-1-100',...., '10100010'].count(-)
should work but it doesn't

Edit2: My second try which also seems to work is:

barcounter = numpy.zeros(8)
for x in range(len(list)):
rankcounter[8-1-list[x].count("-")] += 1
print("barcounter", barcounter)

Answer

I get the sense of what you were going for, but you'll need to loop through the list. Here is a solution that returns a dictionary mapping from number of bars to frequency of which that many bars appeared in a string:

from collections import defaultdict

def get_bar_freq(bar_list):
    bar_freq = defaultdict(int)       # a dictionary that will keep track of frequencies 
    for word in bar_list:
        num_bars = word.count('-')
        bar_freq[num_bars] += 1       # increment freq of this many num_bars
    return bar_freq


def main():
    bar_list = ['-0---110', '--1--110', '01---100', '1--101-0', '10-1-100', '10100010']
    print(get_bar_freq(bar_list))

if __name__ == '__main__':
    main()

This outputs: defaultdict(<class 'int'>, {0: 1, 2: 1, 3: 2, 4: 2}) i.e. it is saying 1 string contained 0 bars, 1 string contained 2 bars, 2 strings contained 3 bars, and 2 strings contained 4 bars.