Python, specific count of chars in string

ε祈祈猫儿з 提交于 2020-01-05 09:03:18

问题


I am trying to count the number of occurrences in a string in python. I would like to take a binary input, say '001101'. Then count the number of 1s, 0s, 11s, 00s etc.

I have tried to implement this by using count, but this will output that there are 3 1s, when i only want it to output 1 1, and 1 11s and for it to not count them individually, unless they are on their own.

I have also tried to implement this with find, but i am having the same problem.

Any help would be appreciated, thanks.


回答1:


You can do the following, using itertools.groupby and collections.Counter:

from itertools import groupby
from collections import Counter

s = '001101011'
c = Counter(''.join(g) for _, g in groupby(s))

c.get('11')
# 2
c.get('1')
# 1
c.get('111', 0)  # use default value to capture count 0 properly
# 0

This groups the string into substrings consisting only of equal chars and performs the counting on those substrings.




回答2:


You could tackle this with regular expressions:

>>> import re
>>> s='001101'

Single ones:

>>> sum(1 for _ in re.finditer('(?<!1)1(?!1)', s))
1

Pairs of ones:

>>> sum(1 for _ in re.finditer('(?<!1)11(?!1)', s))
1

and the same approach applies for groups of zeros.




回答3:


Generic solution if you dont want to specify which sequences of characters to look for.

def count_unique_chars(string):
    char_count = {}
    char = ''

    for pair in zip(list(string), list(string[1:]) + [None]):

        char += pair[0]

        if pair[0] == pair[1]:
            continue

        else:

            if char in char_count.keys():
                char_count[char] += 1
            else:
                char_count[char] = 1

            char = ''

    return char_count

Outputs a dict with the count of unique chars.

count_unique_chars('001101')

{'0': 1, '00': 1, '1': 1, '11': 1}

or

count_unique_chars('001101011000100111101000')

{'0': 3, '00': 2, '000': 2, '1': 3, '11': 2, '1111': 1}

count_unique_chars('hello world')

{' ': 1, 'd': 1, 'e': 1, 'h': 1, 'l': 1, 'll': 1, 'o': 2, 'r': 1, 'w': 1}



来源:https://stackoverflow.com/questions/47286816/python-specific-count-of-chars-in-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!