[英]How to count the difference between two nested lists in Python?
If I had the two following lists with tuples in the form of (x,y): 如果我有以下两个带有(x,y)形式的元组的列表:
[(a,1),(b,2),(c,7),(d,1)]
[(a,3),(b,2),(c,7),(d,8)]
I want to count the number of differences with respect to 'y' value for corresponding 'x' values. 我想针对“ x”值计算相对于“ y”值的差异数。 In the above case, the answer is 2 在上述情况下,答案为2
(a, 1 ) doesn't match with (a, 3 ) (a, 1 )与(a, 3 )不匹配
(d, 1 ) doesn't match with (d, 8 ) (d, 1 )与(d, 8 )不匹配
EDIT: This is not a duplicate, the position of the elements matter. 编辑:这不是重复的,元素的位置很重要。 I want to check if element 1 in list 1 is same as element 1 in list 2 and so on. 我想检查列表1中的元素1是否与列表2中的元素1相同,依此类推。
您可以使用zip
函数和sum
函数中的生成器表达式:
count=sum(i!=j for i,j in zip(list1,list2))
Another method is 另一种方法是
x = [("a", 1) ,("b", 2), ("c", 7), ("d", 1)]
y = [("a", 3), ("b", 2), ("c", 7), ("d", 8)]
count = len(set(x).intersection(y))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.