如何打印一个字符串,显示每个字符在一个字符串中重复的次数?

时间:2019-11-14 15:58:04

标签: python python-3.x algorithm

给出字符串S,如何打印包含重复字符次数的字符串?

例如: 输入:aaabbbbccaa
输出:a3b4c2a2

我的方法:

s = input()

len_string = ''
cur_char = s[0]
cur_counter = 0
for i in range(len(s)):
    if s[i] == cur_char:
        cur_counter += 1
    if s[i] != cur_char or i == len(s) - 1:
        len_string += cur_char + str(cur_counter)
        cur_char = s[i]
        cur_counter = 1

print(len_string)

4 个答案:

答案 0 :(得分:1)

因为您共享了代码,所以这是使用groupby简洁方法:

from itertools import groupby

s = 'aaabbbbccaa'

print(''.join([k + str(len(list(g))) for k, g in groupby(s)]))
# a3b4c2a2

答案 1 :(得分:0)

我会使用collections.Counter https://docs.python.org/2/library/collections.html#counter-objects

Init signature: collections.Counter(*args, **kwds)
Docstring:
Dict subclass for counting hashable items.  Sometimes called a bag
or multiset.  Elements are stored as dictionary keys and their counts
are stored as dictionary values.

>>> c = Counter('abcdeabcdabcaba')  # count elements from a string

>>> c.most_common(3)                # three most common elements
[('a', 5), ('b', 4), ('c', 3)]
>>> sorted(c)                       # list all unique elements
['a', 'b', 'c', 'd', 'e']
>>> ''.join(sorted(c.elements()))   # list elements with repetitions
'aaaaabbbbcccdde'
>>> sum(c.values())                 # total of all counts
15

>>> c['a']                          # count of letter 'a'
5
>>> for elem in 'shazam':           # update counts from an iterable
...     c[elem] += 1                # by adding 1 to each element's count
>>> c['a']                          # now there are seven 'a'
7
>>> del c['b']                      # remove all 'b'
>>> c['b']                          # now there are zero 'b'
0

>>> d = Counter('simsalabim')       # make another counter
>>> c.update(d)                     # add in the second counter
>>> c['a']                          # now there are nine 'a'
9

>>> c.clear()                       # empty the counter
>>> c
Counter()

Note:  If a count is set to zero or reduced to zero, it will remain
in the counter until the entry is deleted or the counter is cleared:

>>> c = Counter('aaabbc')
>>> c['b'] -= 2                     # reduce the count of 'b' by two
>>> c.most_common()                 # 'b' is still in, but its count is zero
[('a', 3), ('c', 1), ('b', 0)]

答案 2 :(得分:0)

我认为有一种方法可以更轻松地完成此操作:

x='aaabbbbccaa'
noreplist = list(dict.fromkeys(x))
countstring=''
for i in noreplist:
   z=z+i+str(x.count(i))
print(countstring)

首先,您将x用作字符串。 然后,使用该字符串中的每个字符创建一个列表,但无需重复任何字符。 最后,只需计算一下char在原始字符串上重复了多少次,并连接到“计数字符串”中。

答案 3 :(得分:0)

#y is a list that contains every character in the string
#z is a list parallel to y but it contains the number of times each element in list y #has 
x=input("Input string: ")
y=[]
z=[]
acc=0
for i in range(len(x)):
    if(x[i] not in y):
        y.append(x[i])
for i in range(len(y)):
    for j in range(len(x)):
        if(y[i]==x[j]):
            acc=acc+1
    z.append(acc)
    acc=0

for k in range(len(y)):
    print(str(y[k])+str(z[k]))