如何计算字符串中项目的重复数?

2024-09-30 01:20:09 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个字符串:s = "hello2020"

如何创建一个返回字符串中重复数的程序?在本例中,当字母“l”多次出现时,程序将返回3,数字“2”和“0”也多次出现

提前谢谢

编辑:到目前为止,我已经尝试过:return len([x for x in set(s) if s.count(x) > 1]),但有两个测试用例失败了。因此,我正在寻找另一种解决办法


Tags: 字符串in程序编辑forlenreturnif
2条回答

一个线性解决方案,将字符串转换为集合,然后用转换后的集合字符串减去字符串的长度

def duplicate_count(string):
    return len(string) - len(set(string))

print(duplicate_count("hello2020"))
#3
from collections import Counter

def do_find_duplicates(x):
    dup_chars = 0
    for key,val in Counter(x).items():
        if val > 1: dup_chars += 1
    print(dup_chars)

do_find_duplicates('hello2020')

相关问题 更多 >

    热门问题