在 python 中查找最匹配的列表



我无法制作一种算法来告诉我一个列表与另一个列表的匹配有多接近。

例如,如果我有以下列表:

a = [-1,2,3]
b = [3,4,4] 
c = [4,-2,-5] 
d = [-3,-4,4] 

我想知道哪个数组与我的测试列表非常相似。

testarray = [3,4,4]

这应该返回列表b,但我的代码有时会返回列表b,有时返回列表d。请帮我编写一个算法,将列表与一堆列表进行比较并返回紧密匹配的列表。

这是我提出的一个超级混乱的定义。希望这能有所帮助。

import copy
#Lists to be tested
a = [-1,2,3]
b = [3,4,4] 
c = [4,-2,-5] 
d = [-3,-4,4] 
#list of lists
lists = [a,b,c,d]
testList = [3,4,4]
def compare(testList,lists):
    #create a list of scores the same length of lists
    scores = []
    for i in range(len(lists)):
        scores.append(0)
    #scores should be [0,0,0,0] now

    for L in lists:
        #create a copy of testList because you will be changing it.
        copyList = copy.deepcopy(testList)
        for val in L:
            #For every value in L, check if it is also in copyList
            if val in copyList:
                #If it is, add to score and delete from copyList.
                #This is so [3,3,3] ends up closer to [3,3,8] than to [3,6,7]
                #This is why we are using a copy of testList
                scores[lists.index(L)]+=1
                del copyList[copyList.index(val)]
print compare(testList,lists)

相关内容

  • 没有找到相关文章

最新更新