[英]Getting output as character and it's occurrence in the string
The input I gave is like this我给的输入是这样的
Input- abccdddeffg
and the output I want is character and it's occurrence number而我想要的 output 是字符,它的出现次数
Output- a1b1c2d3e1f2g1
my code我的代码
uni = []
string = 'abcccdd'
for i in range(0, len(string)):
for j in range(i+1, len(string)):
if (string[i] == string[j]):
uni.append(string[i])
for oc in uni:
cou= uni.count(oc)
print(oc,cou)
Thanks in advance提前致谢
You can use the Counter from collections to get the count of every character in the list.您可以使用 collections 中的计数器来获取列表中每个字符的计数。 Then use a forloop to generate your result and use set to make sure no character is repeated in the result.
然后使用 forloop 生成结果并使用 set 确保结果中没有重复字符。
from collections import Counter
string = "abccdddeffg"
counts = Counter(string)
sets = set()
result = []
for s in string:
if s not in sets:
result.append(f"{s}{counts[s]}")
sets.add(s)
result = ''.join(result)
print(result)
Firstly, your output contains an error, there should be 1
next to e
as it was there in first occurring characters.首先,您的 output 包含一个错误,
e
旁边应该有1
,因为它在第一次出现的字符中。
After clearing this, this is what you need:清除后,这就是您需要的:
import collections
s = "abccdddeffg" # your string
a = dict((letter,s.count(letter)) for letter in set(s))
a = collections.OrderedDict(sorted(a.items()))
answer = "" # to store the result
for i,j in zip(a.keys(),a.values()):
answer+= i + str(j)
print(answer)
Answer
will return: Answer
将返回:
'a1b1c2d3e1f2g1'
Here is a simpler approach:这是一个更简单的方法:
def freq_string(string):
output, buffer = "", ""
for letter in string:
if buffer != letter:
buffer = letter
output += f"{letter}{string.count(letter)}"
return output
Note: this does assume that same characters are in succession rather than spread randomly around the string.注意:这确实假设相同的字符是连续的,而不是在字符串周围随机分布。
Assuming your input string is sorted and has at least one letter, you can do a simple loop to handle it:假设您的输入字符串已排序并且至少有一个字母,您可以执行一个简单的循环来处理它:
if len(string) == 1:
# print out the only string and 1 as its occurences
print(string + '1')
else:
# initialize first string, its counter, and our result string
prev = string[0]
counter = 1
result = ''
# loop over each letter
for letter in string[1:]:
curr = letter
# if current letter is different from previous letter,
# concat the result and refresh our counter
# else just increase the counter
if curr != prev:
result = result + prev + str(counter)
counter = 1
else:
counter = counter + 1
prev = curr
# don't forget to handle the last case
result = result + prev + str(counter)
print(result)
in the simplest way:以最简单的方式:
inp = 'abccdddeffg'
l=[]
o=""
for i in inp:
if i in l:
pass
else:
l.append(i)
o+="{}{}".format(i,inp.count(i))
print(o)
output output
'a1b1c2d3e1f2g1'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.