Python 将列表与列表中的多个列表进行比较

Python 将列表与列表中的多个列表进行比较,python,python-3.x,list,Python,Python 3.x,List,我想将一个列表与存储在一个列表中的多个列表进行比较,得到数据的平均正确性我想将一个列表与35个列表进行比较(对于我的项目),但为了便于理解,我简化为将一个列表与三个列表进行比较。 这是我到目前为止所做的 def获取精度(a、b): #初始化变量以获取和 总计=0.0 #范围为35,因为我有35行数据存储在csv文件中 对于范围(35)内的i: #获取两个列表之间匹配的0和1的数量 f=总和(a!=b表示a,b表示压缩(a,b)) #将匹配的0和1的数量除以较短列表的长度 如果len(a)>len

我想将一个列表与存储在一个列表中的多个列表进行比较,得到数据的平均正确性我想将一个列表与35个列表进行比较(对于我的项目),但为了便于理解,我简化为将一个列表与三个列表进行比较。 这是我到目前为止所做的

def获取精度(a、b):
#初始化变量以获取和
总计=0.0
#范围为35,因为我有35行数据存储在csv文件中
对于范围(35)内的i:
#获取两个列表之间匹配的0和1的数量
f=总和(a!=b表示a,b表示压缩(a,b))
#将匹配的0和1的数量除以较短列表的长度
如果len(a)>len(b):
百分比=f/len(b)*100
其他:
百分比=f/len(a)*100
总数+=百分比
#返回total/35,与35个列表进行比较,得到平均正确率
返回总数/35
l1=[1,0,1,0,0]
l2=[[1,0,1,1,0,1],[1,0,1,1,1,0,1,0,0],[1,0,1,1,0,1,0]]
res=获取精度(l1,l2)
#预期答案应为73.33%
打印(res)

我已经解释了每行代码在完成比较时所做的工作。要将
l1
l2
中的每个列表进行比较,以获得平均匹配正确率,我需要做哪些更改?

我发现了一个简单的示例,可以为您获取列表相似性的百分比:

# initialize lists 
test_list1 = [1, 4, 6, 8, 9, 10, 7] 
test_list2 = [7, 11, 12, 8, 9] 
  
# printing original lists 
print("The original list 1 is : " + str(test_list1)) 
print("The original list 2 is : " + str(test_list2)) 
  
# Percentage similarity of lists 
# using "|" operator + "&" operator + set() 
res = len(set(test_list1) & set(test_list2)) / float(len(set(test_list1) | set(test_list2))) * 100
  
# printing result 
print("Percentage similarity among lists is : " + str(res)) 
如果您可以使用库difflib的序列匹配器,则更容易获得相似性比率:

import difflib
sm=difflib.SequenceMatcher(None,a,b)
sm.ratio()
使用difflib的最终版本可能如下所示:

import difflib

def get_accuracy(a,b):
    result = 0.0
    for list_contained in b:
        sm = difflib.SequenceMatcher(None, a, list_contained)
        result += sm.ratio()
    return result / len(b)

l1=[1,0,1,0,0]
l2=[[1,0,1,1,0,1],[1,0,1,1,1,0,1,0,0],[1,0,1,1,0,1,0]]
res=get_accuracy(l1,l2)
print(res)

假设您的代码适用于单个列表,这应该可以

def get_accuracy(a, b):
    sum = 0
    length = len(b)
    for list_in_b in b:
      # Initialize variable to get sum 
      total = 0.0
      # Range of 35 because i have 35 lines of data stored in csv file
      for i in range(35):
         # Get the number of matching zeros and ones between 2 lists
         f = sum(a != b for a, b in zip(a, list_in_b))
         # Divide the number of matched zeros and ones with length of the shorter list
         if len(a) > len(list_in_b):
            percentage = f / len(list_in_b ) * 100
         else:
            percentage = f / len(a) * 100
         total += percentage
      sum += total/35
     
    #Return total/35 to get the average correctness after comparing with 35 lists
    return sum / length
这应该做到:

f = sum(i != j for i, j in zip(a, b[i]))

我用
l1=[1,0,1,0,0]l2=[[1,0,1,1,0,1],[1,0,1,0,1,0,0],[1,0,1,1,1,0,1,0],[1,1,1,0,1,0,0]。
结果是26.67%,而不是73.33%。[[1,0,1,1,0,0,0,1]。]l2=[1,0]。我编辑了代码,我把你的问题理解为35张清单,里面有35个项目,我的错:)你好,你有时间检查我的回答吗?如果它对你有用,请考虑它的投票和/或选择它作为最终答案。谢谢你的时间!