简体   繁体   English

比较两个在Python中顺序和重复很重要的浮点列表

[英]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. 我需要知道如何类似listBlistA ,不只是它包含相同的值,但在相同的位置的值。

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. 在这种情况下,前两个条目是精确的,但是索引2和3处的条目是不同的-因此,两个列表之间存在2个差异。

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 . 给出2预期输出。

Note that because your problem description states that order is important, sets will be no use here as they are not ordered. 请注意,由于问题描述指出顺序很重要,因此在这里没有使用集合,因为它们没有顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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