繁体   English   中英

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

[英]how to print a string showing the number of times each character is repeated in a string?

给定一个字符串 S,如何打印一个包含该字符重复次数的字符串?

例如:输入:aaabbbbccaa
output: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)

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

from itertools import groupby

s = 'aaabbbbccaa'

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

我会使用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)]

我认为有一种方法可以更轻松地做到这一点:

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

首先,你有 x 那是你的字符串。 然后,您使用该字符串中的每个字符制作一个列表,但不重复任何字符。 最后,只计算该字符在原始字符串上重复的次数,并在“计数字符串”中连接。

#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]))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM