![](/img/trans.png)
[英]Python 3.x: How to compare two lists containing dictionaries where order doesn't matter
[英]Compare two lists of floats where order and duplicates matter in Python
我想比较两个列表之间的位置和值的差异。 我需要知道如何类似listB
是listA
,不只是它包含相同的值,但在相同的位置的值。
from collections import Counter
listA = [0.01, 0.02, 0.04, 0.03]
listB = [0.01, 0.02, 0.03, 0.04]
def compareListMethod1(a, b):
return set(a).intersection(b)
def compareListMethod2(a, b):
c1 = Counter(a)
c2 = Counter(b)
diff = c1-c2
return list(diff.elements())
def compareListMethod3(a, b):
count = Counter(a) # count items in a
count.subtract(b) # subtract items that are in b
diff = []
for x in a:
if count[x] > 0:
count[x] -= 1
diff.append(x)
return diff
print(compareListMethod1(listA, listB)) # returns {0.02, 0.01, 0.04, 0.03}
print(compareListMethod2(listA, listB)) # returns []
print(compareListMethod3(listA, listB)) # returns []
期望的输出将揭示两个列表彼此不同的次数。 在这种情况下,前两个条目是精确的,但是索引2和3处的条目是不同的-因此,两个列表之间存在2个差异。
感谢您的指导!
如果我正确理解,这应该可以工作:
sum(a != b for a, b in zip(listA, listB))
给出2
预期输出。
请注意,由于问题描述指出顺序很重要,因此在这里没有使用集合,因为它们没有顺序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.