[英]How can i check if a string has some of the same characters in it in Python?
In my program, when a user inputs a word, it needs to be checked for letters that are the same. 在我的程序中,当用户输入单词时,需要检查单词是否相同。
For example, in string = "hello"
, hello has 2 'l's. 例如,在
string = "hello"
,hello具有2'l。 How can i check for this in a python program? 我如何在python程序中检查此内容?
Use a Counter
object to count characters, returning those that have counts over 1. 使用
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)]
You can accomplish this with 您可以使用
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'))
which yields 产生
{'l': 2, 'o': 5}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.