比较字符串中的字符

时间:2016-06-22 04:05:15

标签: python string python-3.x comparison character

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

例如,

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(

)将其转换为int
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

这也会返回相同的错误。

当我打印列表(一个)[1]!= list(two)[1]时,eithers返回True或False,因为比较是正确的。

您能告诉我如何为此目的纠正我的代码吗?

11 个答案:

答案 0 :(得分:3)

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

a='HORSE'
b='TIGER'


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

压缩对将index-for-index列在一起,当一个用完时停止。列表推导是基本紧凑for-statements的生成器,您可以添加逻辑。所以它基本上是这样的:对于每个压缩的字母对(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()。

答案 1 :(得分:2)

sum([int(i!=j) for i,j in zip(a,b)])可以解决问题

答案 2 :(得分: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

另外,一般样式是小写函数名称(通常是动词)和标题大小写类名称(通常是名词):)

答案 3 :(得分: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

这里你唯一要做的就是检查字符串的大小。在我的示例中,如果a大于b,则会有IndexError

答案 4 :(得分: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

答案 5 :(得分: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

答案 6 :(得分:0)

有几个问题:

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

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

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)但这对于您尝试的内容来说效率低下实现

答案 7 :(得分: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
祝你好运!

答案 8 :(得分:0)

a = "HORSE"
b = "TIGER"
a_list=[]
b_list=[]
for l in a_list:
    a_list.append(l)

for k in b_list:
    b_list.append(k)

difference = len(a)
for i in a_list:
    for x in b_list:
        if a_list[i] == b_list[x]:
            difference = difference - 1

print(difference)

看看是否有效:)

答案 9 :(得分:0)

这太简单了:

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

答案 10 :(得分: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")

相关问题