在python中查找最匹配的列表

时间:2014-02-20 19:46:45

标签: python list compare

我在编写算法时遇到问题,该算法会告诉我一个列表与另一个列表的匹配程度是多少。

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

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

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

testarray = [3,4,4]

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

1 个答案:

答案 0 :(得分:0)

这是我掀起的超级凌乱的定义。希望这可以提供帮助。

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)