Python 将字符串差异与字符串列表进行比较

Python 将字符串差异与字符串列表进行比较,python,string,list,Python,String,List,我有一个方法,计算两个字符串中的差异数,并在差异所在的位置输出 def method(a): count=0 s1="ABC" for i in range (len(a)): if not a[i]==s1[i]: count=count+1 else: count=count+0 return a,count,difference(a, s1) 在输入ex CBB时,此方法输出

我有一个方法,计算两个字符串中的差异数,并在差异所在的位置输出

def method(a):
    count=0
    s1="ABC"
    for i in range (len(a)):
        if not a[i]==s1[i]:
            count=count+1
        else:
            count=count+0
    return a,count,difference(a, s1)
在输入ex CBB时,此方法输出

('CBB', 2, [1, 0, 1])
我真正需要的是让这个方法也这样做,但是where is不仅与s1中的单个字符串进行比较,还与字符串列表进行比较

s1 = ['ACB', 'ABC', 'ABB']

有人用智能方法来做这件事吗?

好的,澄清后,不要硬编码s1,让你的方法把它作为参数:

def method(a, s1):
    count=0
    for i in range (len(a)):
        if not a[i]==s1[i]:
            count=count+1
        else:
            count=count+0
    return a,count,difference(a, s1)
然后使用列表压缩:

 result = [method(a, s1) for s1 in list]

但是要小心,因为如果a大于s1,您的方法将失败。在这种情况下,由于您实际上没有说明结果应该是什么,所以我将其保持原样。

函数
compare
计算差异的数量(以及您使用
difference()
创建的差异映射)。我重写了compare函数以获取一个要与之进行比较的基本字符串,
src
,这样您就不会一直与
“ABC”
进行比较

def compare(src, test):
    if len(src) != len(test):
        return # must be the same length
    diffmap = [0]*len(src)
    count = 0
    for i, c in enumerate(src):
        if not c == test[i]:
            count = count+1
            diffmap[i] = 1
    return test, count, diffmap
compare\u to_many
函数只需遍历要比较的字符串列表,
srcs
,并创建这些基本字符串和测试字符串之间的比较列表
test

def compare_to_many(srcs, test):
    return map(lambda x: compare(x, test), srcs)
编辑: 在注释中澄清后,@X-Pender需要对源列表进行硬编码。这可以通过以下单一功能反映出来:

def compare(test):
    def compare_one(src, test):
        diffmap = [0]*len(src)
        count = 0
        for i, c in enumerate(src):
        if not c == test[i]:
            count = count+1
            diffmap[i] = 1
        return test, count, diffmap
    sources = ["ABC", "CDB", "EUA"] # this is your hardcoded list
    return map(lambda x: compare_one(x, test), sources)

这会将多个测试字符串与单个基本字符串进行比较,但X-Pender想要的是将一个测试字符串与多个基本字符串进行比较。该函数应该只接受一个参数,并且列表应该是硬编码的。原因是什么?每次你打电话给客户时,你都可以通过相同的列表function@X-Pender然后将其重命名为method2,保持方法签名不变,并从方法调用method2。您应该在问题中提到这是一个家庭作业。不告诉别人就让别人做作业是不酷的。