计算字符串 Python 中的常见字符 [英] Count Common Characters in Strings Python

查看:72
本文介绍了计算字符串 Python 中的常见字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码的输出仍然是 4.但是,输出应该是 3.存在集合交集,因为我相信这是答案的关键.答案是 4 而不是 3 的原因来自于 s1 中与 s2 匹配的 2 个 qs 和 1 个 r 的数量.

The output of this code continues to be 4. However, the output should be 3. The set intersection is present because I believe that is the key towards the answer. The reasoning for the answer being 4 instead of 3 comes from the number of 2 qs and 1 r that match s2 in s1.

s2 = "qsrqq"
s1 = "qqtrr"
counts1=0
counts2=0
letters= set.intersection(set(s1), set(s2))
for letter1 in set(s1):
    counts1 += s2.count(letter1)
for letter2 in set(s2):
    counts2 += s1.count(letter2)


counts = min(counts1, counts2)
print (counts)

非常感谢任何帮助.

推荐答案

如果你想保持一个共同字符数的计数,你应该使用 collections.Counter 而不是 set.

If you want to maintain a count of the number of characters in common, you should use collections.Counter instead of set.

from collections import Counter

s2 = 'qsrqq' 
s1 = 'qqtrr'

common_letters = Counter(s1) & Counter(s2)  # => {'q': 2, 'r': 1}
print(sum(common_letters.values()))         # => 3

这篇关于计算字符串 Python 中的常见字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆