Python比较两个字符串并检查它们共有多少个字符 [英] Python compare two strings and check how many chars they have in common

查看:91
本文介绍了Python比较两个字符串并检查它们共有多少个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道如何检查两个字符串共有多少个字符.例如,如果我有汽车"和汽车",则结果应为3.

I'm just wondering how I can check how many chars two string have in common. For example if I have "car" and "cars", the result should be 3.

有人知道吗?

预先加油并感谢

最大

推荐答案

以下是使用 计数器 .我们为每个单词创建一个 Counter ,然后找到这些 Counter 的交集.那本身就是一个 Counter ,我们可以对这些值求和以找到共享字符的数量

Here's a solution using Counter. We make a Counter for each of the words, then find the intersection of those Counters. That itself is a Counter, and we can just sum the values to find the number of shared characters

from collections import Counter

def shared_chars(s1, s2):
    return sum((Counter(s1) & Counter(s2)).values())

print(shared_chars('car', 'carts'))

将打印

3

如果是 Counter ,则相交是相应计数的最小值.

In case of Counter, intersection is the minimum of corresponding counts.

>>> Counter('abbb') & Counter('bcc')
Counter({'b': 1})

这篇关于Python比较两个字符串并检查它们共有多少个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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