首页 > 解决方案 > 字符串中唯一字符的计数和返回值

问题描述

我在开发一个函数来计算和返回字符串中字符的值时遇到问题。不能使用集合、列表或字典。例如,字符串是 AAACCD,应该返回 3A 2C 1D。

def uniqueValues(string):
count = 0
for s in string:
    if s in "ABCDEFGHIJKL":
        count +=1
return count
print(uniqueValues("AAACCD"))

这只会显示输出 6,即字符串的字符数。

标签: pythonfunctioncount

解决方案


像这样的东西?您可以使用str.count()

def get_counts(s):
    out = ''
    for i in s:
        if i not in out:
            cnt = str(s.count(i))
            out+=(cnt+i+' ')

    return out.strip()

get_counts(s)
'3A 2C 1D'

推荐阅读