6

我需要编写一个代码来分割字符串(这是一个输入),将它附加到一个列表中,计算每个字母的数量 - 如果它与它之前的字母相同,请不要将它放在列表中,而是增加该字母在前一个中的出现次数。嗯,这应该是这样的:

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

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

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 

谢谢!

4

3 回答 3

19

使用Collections.Counter(), dictionary 是一种更好的存储方式:

>>> 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]]
于 2012-11-02T14:56:49.467 回答
2
last = ''
results = []
word = 'assassin'
for letter in word:
if letter == last:
    results[-1] = (letter, results[-1][1] +1)
else:
    results.append((letter, 1))
    last = letter

print result # [('a', 1), ('s', 2), ('a', 1), ('s', 2), ('i', 1), ('n', 1)]
于 2012-11-02T15:45:25.880 回答
1

仅使用内置函数:

def cnt(s):
    current = [s[0],1]
    out = [current]
    for c in s[1:]:
        if c == current[0]:
            current[1] += 1
        else:
            current = [c, 1]
            out.append(current)
    return out

print cnt('assassin')
于 2012-11-02T15:06:15.637 回答