繁体   English   中英

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

[英]How can i check if a string has some of the same characters in it in Python?

在我的程序中,当用户输入单词时,需要检查单词是否相同。

例如,在string = "hello" ,hello具有2'l。 我如何在python程序中检查此内容?

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

from collections import Counter

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

In [482]: get_duplicates('hello')
Out[482]: [('l', 2)]

In [483]: get_duplicates('helloooo')
Out[483]: [('l', 2), ('o', 4)]

您可以使用

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}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM