String 如何在Python中检查字符串中是否包含一些相同的字符?

String 如何在Python中检查字符串中是否包含一些相同的字符?,string,python-3.x,String,Python 3.x,在我的程序中,当用户输入一个单词时,需要检查是否有相同的字母 例如,在string=“hello”中,hello有两个'l'。如何在python程序中检查这一点?使用计数器对象对字符进行计数,返回计数超过1的字符 from collections import Counter def get_duplicates(string): c = Counter(string) return [(k, v) for k, v in c.items() if v > 1] 您可

在我的程序中,当用户输入一个单词时,需要检查是否有相同的字母


例如,在
string=“hello”
中,hello有两个'l'。如何在python程序中检查这一点?

使用
计数器
对象对字符进行计数,返回计数超过1的字符

from collections import Counter

def get_duplicates(string):
    c = Counter(string)
    return [(k, v) for k, v in c.items() if v > 1]


您可以使用

d = defaultdict(int)

def get_dupl(some_string):
    # iterate over characters is some_string
    for item in some_string:
        d[item] += 1
    # select all characters with count > 1
    return dict(filter(lambda x: x[1]>1, d.items()))

print(get_dupl('hellooooo'))
产生

{'l': 2, 'o': 5}

使用计数器,查找计数超过1的所有字符?欢迎使用堆栈溢出。你已经试过做什么了?请复习。堆栈溢出不是编码服务。您需要研究您的问题,并在发布之前尝试自己编写代码。如果你在某个特定的问题上遇到困难,请回来写一份报告和你所做的总结,这样我们可以提供帮助。
{'l': 2, 'o': 5}