【问题标题】:Finding most closely matching list in python在python中查找最匹配的列表
【发布时间】:2014-02-20 19:46:45
【问题描述】:

我无法制定一种算法来告诉我一个列表与另一个列表的匹配程度。

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

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

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

testarray = [3,4,4]

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

【问题讨论】:

  • 这些是列表; Python 中的 array 类型是完全不同的对象类型。
  • 您的距离指标是多少?差异的总和?差异的数量?均方根误差?
  • 在您当前的算法中提供代码将有助于非常
  • 用外行的话来说@DonaldMiner 所说的:你说“什么数组非常相似”,但是有多种方法可以定义一个列表与另一个列表“非常相似”的程度。例如,可以说[1,2,3,4,5,6,7,8,9,10][2,3,4,5,6,7,8,9,10,11] 非常相似,因为您只需删除开头的1 并在第一个列表的末尾添加11,它们是相等的。另一方面,另一个人可能会说它们不相似,因为同一索引处的元素都是不同的。

标签: python list compare


【解决方案1】:

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

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    • 2014-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-12
    相关资源
    最近更新 更多