python - 字符串中唯一字符的计数和返回值
问题描述
我在开发一个函数来计算和返回字符串中字符的值时遇到问题。不能使用集合、列表或字典。例如,字符串是 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,即字符串的字符数。
解决方案
像这样的东西?您可以使用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'
推荐阅读
- rest - 我怎样才能拥有在 React Native 中并不总是定义的动态图像 uri?
- java - 如何在android中创建多语言应用程序
- gem5 - 如何在 Linux 下获得几个 gem5 全系统用户态基准程序的统计信息,而无需多次重启?
- javascript - 快递不设置Cookie
- java - Jenkins 错误:- [错误] 读取 /home/oci/.m2/repository/org/apache-extras/beanshell/bsh/2.0b6/bsh-2.0b6.jar 时出错;无效的 LOC 标头(错误的签名)
- graphql - 弃用 ApolloServer 中的类型
- c# - StreamReader 不会从 NetworkStream 中检索所有内容(TCP 和 C#)
- javascript - 用javascript计算多个输入值
- c# - LINQ中First()和Key的区别
- r - 数字(nrowz)错误:map()函数的“长度”参数无效