简体   繁体   中英

Compare two lists of floats where order and duplicates matter in Python

I want to compare the position and the differences in value between the two lists. I need to know how similar listB is to listA , not just does it contain the same values, but are those values in the same positions.

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

The desired output would reveal how many times the two lists were different from one another. In this case, the first two entries are exact, but the entries at index 2 and 3 are different - so there exist 2 differences between the two lists.

Thank you for any and all guidance!

If I understand correctly, this should work:

sum(a != b for a, b in zip(listA, listB))

Gives expected output of 2 .

Note that because your problem description states that order is important, sets will be no use here as they are not ordered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM