比较字符串中的字符

新手上路,请多包涵

我正在尝试创建一个函数来比较两个相同长度的字符串的相同位置的字符并返回它们的差异计数。

例如,

 a = "HORSE"
b = "TIGER"

它会返回 5(因为同一位置的所有字符都不同)

这就是我一直在做的事情。

 def Differences(one, two):
    difference = []
    for i in list(one):
        if list(one)[i] != list(two)[i]:
            difference = difference+1
    return difference

这给出了一个错误“列表索引必须是整数而不是字符串”

所以我尝试使用 int(ord(

 def Differences(one, two):
    difference = 0
    for i in list(one):
        if int(ord(list(one)[i])) != int(ord(list(two)[i])):
            difference = difference+1
    return difference

这也返回相同的错误。

当我打印 list(one)[1] != list(two)[1] 时,它会返回 True 或 False,因为比较是正确的。

你能告诉我如何为此目的更正我的代码吗?

原文由 Denis Moura 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 774
1 个回答

我可能只是用 zip 和列表理解同时迭代它们两个,然后获取列表的长度:

 a='HORSE'
b='TIGER'

words=zip(a,b)
incorrect=len([c for c,d in words if c!=d])
print(incorrect)

压缩对列表一起索引索引,当一个用完时停止。列表理解是生成器,它们 基本上 是紧凑的 for 语句,您可以向其中添加逻辑。所以它基本上是这样写的:对于每个压缩的字母对 (c,d) if c!=d then put a into the list (so if the letters are different, we increase the list length by 1).然后我们只取列表的长度,即所有位置不同的字母。

如果我们认为缺失的字母不同,那么我们可以使用 itertools.zip_longest 来填充单词的其余部分:

 import itertools

a='HORSES'
b='TIG'

words=itertools.zip_longest(a,b,fillvalue=None)
incorrect=len([c for c,d in words if c!=d]) ## No changes here
print(incorrect)

显然,None 永远不会等于一个字符,因此将记录长度差异。

编辑:这没有被提及,但如果我们想要不区分大小写,那么您只需预先在字符串上运行 .lower() 或 .casefold() 。

原文由 Reid Ballard 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题