比较字符串中的字符

Den*_*ura 2 python string comparison character python-3.x

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

例如,

a = "HORSE"
b = "TIGER"
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

所以我尝试使用 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
Run Code Online (Sandbox Code Playgroud)

这也返回相同的错误。

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

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

Rei*_*ard 6

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

a='HORSE'
b='TIGER'


words=zip(a,b)
incorrect=len([c for c,d in words if c!=d])
print(incorrect)
Run Code Online (Sandbox Code Playgroud)

压缩对列出索引对索引,当一个用完时停止。列表推导式生成器基本上是紧凑的 for 语句,您可以向其中添加逻辑。所以它基本上是:对于每个压缩的字母对 (c,d) 如果 c!=d 然后将 a 放入列表中(因此如果字母不同,我们将列表长度增加 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)
Run Code Online (Sandbox Code Playgroud)

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

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