简体   繁体   English

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

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

Given a string S, how to print a string containing number of times the character is repeated?给定一个字符串 S,如何打印一个包含该字符重复次数的字符串?

for example: input: aaabbbbccaa例如:输入:aaabbbbccaa
output: a3b4c2a2 output:a3b4c2a2

my approach:我的方法:

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)

Because you have shared your code, here is one concise way using groupby :因为您已经共享了代码,所以这是使用groupby的一种简洁方法:

from itertools import groupby

s = 'aaabbbbccaa'

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

I would use collections.Counter https://docs.python.org/2/library/collections.html#counter-objects我会使用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)]

I think there is a way to do this much more easy:我认为有一种方法可以更轻松地做到这一点:

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

First, you have x that is your string.首先,你有 x 那是你的字符串。 Then you make a list with every char from that string, but without repeating any char.然后,您使用该字符串中的每个字符制作一个列表,但不重复任何字符。 And last, just counts how many times is that char repeated on the original string, and concatenate in a 'count string'.最后,只计算该字符在原始字符串上重复的次数,并在“计数字符串”中连接。

#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.

相关问题 如何打印字符串中每个字母出现的次数? - How can i print number of times each alphabet occurs in the string? 计算每个单词在一个字符串中重复的次数? - Count number of times each word has repeated in a string? 查找字符串中每个字符出现的次数的复杂性 - complexity in finding the number of times each character is present in a string 如何找到一个单词在给定字符串中连续重复的最大次数? - How to find the largest number of times a word is repeated consecutively in a given string? 在字符串中查找重复的字符,并确定在python中重复连续的次数 - Find a repeated character in a string and determining how many times in a row it is repeated in python 如何在pandas列中的每个重复的字符串值后面添加计数器编号? - How to append counter number to each repeated string value in pandas column? 显示并返回函数上重复字符串的数量? - Showing and returning the number of a repeated string on a function? 如何在一行上打印一定次数的字符串然后移动到新行 - how to print a string a certain number of times on a line then move to a new line 如何编写一个递归函数来打印字符串一定次数? - How to write a recursive function to print a string a certain number of times? YAML - 多次打印字符串 - YAML-Print string a number of times
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM