计算字符串中的连续字符 [英] Counting consecutive characters in a string

查看:98
本文介绍了计算字符串中的连续字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个代码,将字符串(作为输入)切成薄片,将其附加到列表中,计算每个字母的数量-如果它与之前的字母相同,则不要将其放入列表,但是要增加前一个字母的出现次数。.
这应该是这样的:

I need to write a code that slices the string (which is an input), append it to a list, count the number of each letter - and if it is identical to the letter before it, don't put it in the list, but rather increase the appearance number of that letter in the one before.. Well this is how it should look like :

assassin [['a', 1], ['s', 2], ['a', 1], ['s', 2]], ['i', 1], ['n', 1]

刺客一词只是一个例子。.
到目前为止,我的代码是这样的:

the word assassin is just an example of the need.. My code so far goes like this:

userin = raw_input("Please enter a string :")
inputlist = []
inputlist.append(userin)
biglist = []
i=0
count = {}
while i<(len(userin)):
    slicer = inputlist[0][i]
    for s in userin:
        if count.has_key(s):
            count[s] += 1
        else:
            count[s] = 1
    biglist.append([slicer,s])
    i = i+1
print biglist 

谢谢!

推荐答案

使用 Collections.Counter() ,字典是更好的存储方式:

Use Collections.Counter(), dictionary is a better way to store this:

>>> from collections import Counter
>>> strs="assassin"
>>> Counter(strs)
Counter({'s': 4, 'a': 2, 'i': 1, 'n': 1})

或使用 itertools.groupby()

>>> [[k, len(list(g))] for k, g in groupby(strs)]
[['a', 1], ['s', 2], ['a', 1], ['s', 2], ['i', 1], ['n', 1]]

这篇关于计算字符串中的连续字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆