[英]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.