比较字符串中的字符

3

我将尝试创建一个函数来比较两个长度相同的字符串中相同位置的字符,并返回它们不同之处的数量。

例如,

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,因为比较是正确的。

你能告诉我如何纠正我的代码以实现这个目的吗?


你收到错误的原因是因为你正在使用for循环迭代字符串。在Python中,当你迭代某样东西时(另外说一句,你不需要将字符串转换为列表;在Python中,字符串本来就是可迭代的),你会得到该项中的每个子项(而不是索引号)。因此,在你的for循环中,你得到了["H","O","R","S","E"]作为“i”的值,这显然不是索引(即0、1、2、3、4)。 - Reid Ballard
11个回答

7
我会使用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),如果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)

显然,None永远不会等于一个字符,所以长度上的差异会被记录下来。

编辑:虽然没有提到,但如果我们想要不区分大小写,那么只需在字符串之前运行.lower()或.casefold()。


2

sum([int(i!=j) for i,j in zip(a,b)]) 可以实现这个功能。


该代码用于计算两个列表 a 和 b 中,对应位置不相等的元素个数之和。

这很好而且简洁;只是提醒未来的读者,如果输入的长度不同,这将导致不准确性。zip也不会引发异常。 - Jordan Bonitatis

1
使用zip对两个字符串进行连续迭代。
>>> def get_difference(str_a, str_b):
...     """
...     Traverse two strings of the same length and determine the number of 
...     indexes in which the characters differ
...     """
...
...     # confirm inputs are strings
...     if not all(isinstance(x, str) for x in (str_a, str_b)):
...         raise Exception("`difference` requires str inputs")
...     # confirm string lengths match
...     if len(str_a) != len(str_b):
...         raise Exception("`difference` requires both input strings to be of equal length")
...
...     # count the differences; this is the important bit
...     ret = 0
...     for i, j in zip(str_a, str_b):
...         if i != j:
...             ret += 1
...     return ret
... 
>>> difference('HORSE', 'TIGER')
5

此外,通常的风格是将函数名(通常是动词)转换为小写,并将类名(通常是名词)转换为标题大小写。 :)

0

a = ['a' , 'b'  , 'c' , 'd' , 'd' , 'c']
b = ['a' , 'b' , 'c' ]
index = []

if len(a) == len(b):
    for i in range(len(a)):
            if a[i]!=b[i]:
                index.append(a[i])
    if len(index) > 0:
        print("The array is not same")

    else:
        print("The array is same")

else:
    print("The array is not same")


嗨,bhagyashree bhaya。你应该在代码片段旁边添加一些解释来更好地理解为什么这是一个好的答案。也许还可以简要说明为什么选择这种方式。最好的问候! - klaas

0

亲自尝试发现吧

>>> a = "HORSE"
>>> list(a)
['H', 'O', 'R', 'S', 'E']
>>> list(a)[2]
'R'
>>> for i in list(a):
...     i
...
'H'
'O'
'R'
'S'
'E'
>>> list(a)['R']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str

祝你好运!


0

这太简单了:

def Differences(one, two):
    difference = 0
    for char1, char2 in zip(one, two):
        if char1 != char2:
            difference += difference
    return difference

0
你可以像这样做:
def getDifferences(a,b):
  count = 0

  for i in range(0, len(a)):
    if a[i] is not b[i]:
      count += 1

  return count

这里你唯一需要自己实现的是检查字符串的大小。在我的例子中,如果 ab 大,则会引发一个 IndexError

0

试一下这个:

def Differences(one, two):
    if len(two) < len(one):
        one, two = two, one
    res = len(two) - len(one) 
    for i, chr in enumerate(one):
        res += two[i] != chr
    return res

在编程中,重要的是首先检查它们的大小,以防第二个字符串比第一个短,这样就不会出现IndexError错误。


0

就复杂度和运行时间而言,每次迭代调用list()都不是很高效,因为它会分割字符串、分配内存等等...

正确的做法是迭代列表的索引,然后通过索引进行比较,类似于:

def str_compare(l1, l2):
   assert len(l1) == len(l2) , 'Lists must have the same size'        
   differ_cnt = 0
   for i in xrange(len(l1)):
       if l1[i] != l2[i]:
           differ_cnt += 1
   return differ_cnt

0

以下是几个问题:

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

首先,当您调用Differences(a, b)时,list(one)['H', 'O', 'R', 'S', 'E'],因此您正在迭代字符串而不是整数。将您的代码更改为:
for i in range(len(one)):

将迭代整数0-4,这只适用于您的情况,因为ab具有相同的长度(如果要处理不同长度的输入,则需要想出更好的解决方案)。

其次,您不能向数组添加内容,因此应将其更改为int,然后再进行添加。结果如下:

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

如果你非常想使用数组,你可以将元素添加到数组中:difference.append(1),然后返回数组的长度:return len(difference)。但是,这对于你想要实现的目标来说效率不高。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接