Python - 查找同时在 string1 和 string2 中找到的字符数

标签 python

我正在尝试查找第一个字符串中也存在于第二个字符串中的字符数。这是我目前所拥有的:

def main():
    text1 = raw_input("Enter word 1: ")
    text2 = raw_input("Enter word 2: ")

    print("The number of characters that occur in both", text1, "and", text2, "is", count)

def count(text1, text2):
    char = 0
    for i in text1:
        for j in text2:
            if i == j:
                char += 1

    return char

main()

我在 def count() 上遇到了问题。我不确定如何计算 text1 和 text2 中出现的不会重复的字母数量。感谢您的帮助!

最佳答案

使用set.intersection :

(set(text1).intersection(item2))

In [22]: len(set("bana").intersection("banana"))
Out[22]: 3

intersection() 将接受任何可迭代对象作为参数。

def count(text1, text2):
    return len(set(text1).intersection(text2))
In [24]: count("foo","foobar")
Out[24]: 2

如果你想要重复:

def count(text1, text2):
    s = set(text2)
    return len([x for x in text1 if  x in s])
In [29]: count("foo","foobar")
Out[29]: 3

In [30]: count("bana","banana")
Out[30]: 4

关于Python - 查找同时在 string1 和 string2 中找到的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25071675/

相关文章:

python - 测试 IRC 机器人

python - cv2.VideoCapture错误

python - 如何以非矢量化方式计算Python中批量图像的平均值?

python - 如何判断一个 Sprite 是否正在接触pygame中的另一个 Sprite

python - 'str' 对象没有属性 'dt'

python - 无需重新从python中的字符串中提取数字

python - Autobahn websocket 服务器的 ConnectionRequest.headers 中的所有 http header key 均以小写形式出现

python - PySpark:如何在 PySpark SQL 中创建计算列?

python - 如何在 python 中从这个 GUI 调用另一个 ".py"?

python - 如何创建 "Solid" block ? pygame