gpt4 book ai didi

python - 如何检查一个变量与另一个变量共有多少个字符

转载 作者:行者123 更新时间:2023-11-28 20:57:12 25 4
gpt4 key购买 nike

如果我有两个变量,我想看看它们有多少个相同的字符,我该怎么做才能得出有多少个是错误的?例如:

a = "word"
b = "wind"
a - b = 2

有没有办法做到这一点或使上面的工作起作用?

编辑:计算时还应考虑顺序

Edit2:所有这些结果应该如下所示

a = bird
b = word
<program to find answer> 2


a = book
b = look
<program to find answer> 3


a = boat
b = obee
<program to find answer> 0

a = fizz
b = faze
<program to find answer> 2

最佳答案

这可能不适用于所有情况,但如果您想比较字符,可以使用 set :

a = "word"
b = "wind"

diff = set.intersection(set(a),set(b))
print(len(diff))
>> 2

这会忽略序列,因为您将它们分组为一组独特的字符。

您可以使用的另一个有趣的 Python 标准模块库是 difflib .

from difflib import Differ

d = Differ()

a = "word"
b = "wind"

[i for i in d.compare(a,b) if i.startswith('-')]
>>['- o', '- r']

difflib本质上为您提供了比较字符串等序列的方法。来自Differ上面的对象,您可以比较 2 个字符串并识别添加或删除的字符以跟踪字符串 a 的更改到字符串 b .在给出的示例中,列表理解用于过滤掉从 a 中删除的字符至 b , 您还可以检查以 + 开头的字符对于添加的字符。

[i for i in d.compare(a,b) if i.startswith('+')]
>>['+ i', '+ n']

或两个序列寻址共有的字符

How to check how many characters a variable has in common with another variable

common = [i for i in d.compare(a,b) if i.startswith('  ')]
print(common, len(common))
>> [' w', ' d'] 2

您可以阅读有关 Differ 的更多信息对象 here

关于python - 如何检查一个变量与另一个变量共有多少个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53599656/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com