简体   繁体   中英

Python compare 2 lists filled with 3-tuples

I have 2 lists each filled with the 3-tuples.

In the beginning they will be equal:

a = [(1,1,123),(1,2,124),(2,1,231),(2,2,123)]
b = [(1,1,123),(1,2,124),(2,1,231),(2,2,123)]

Case 1:

An extra element is added to b at the end

a = [(1,1,123),(1,2,124),(2,1,231),(2,2,123)]
b = [(1,1,123),(1,2,124),(2,1,231),(2,2,123),(3,1,123)]

Return: Added (3,1,123)

Case 2

Element 2 in b changes from 124 -> 123

a = [(1,1,123),(1,2,124),(2,1,231),(2,2,123)]
b = [(1,1,123),(1,2,123),(2,1,231),(2,2,123)]

Return: Changed a[1] to (1,2,123)

Case 3

A combination of Case 1 and 2, an extra element is added to b and element 2 in b changes from 124 -> 123

a = [(1,1,123),(1,2,124),(2,1,231),(2,2,123)]
b = [(1,1,123),(1,2,123),(2,1,231),(2,2,123),(3,1,123)]

Return: Added (3,1,123) and Changed a[1] to (1,2,123)

In all the cases a==b returns False, what I'm trying to do is figure out how to compare the lists and find whether an element was added, changed, or both. Looking for any suggestions.

changed = False
added = len(tuple1) != len(tuple2)
for e1, e2 in zip(tuple1, tuple2):
    if e1 != e2:
        changed = True
return changed, added, a==b

This is before the edit. This will check to see if added, changed, or the same and return three booleans accordingly.

tuple1 = [(1,1,123),(1,2,124),(2,1,231),(2,2,123)]
tuple2 = [(1,1,123),(1,2,124),(2,1,231),(2,2,13), (0,0)]
changed = False
info = ""
if len(tuple1) != len(tuple2):
    info += "Added " + str(tuple2[-1])
for e1, e2 in zip(tuple1, tuple2):
    if e1 != e2:
        info += " Changed a[" + str(tuple2.index(e2)) + "] to " + str(e2)
print(info)

prints ---> "Added (0, 0) Changed a[3] to (2, 2, 13)"

The above code is post edit and will work in any instance where only one element is added and the element is added to the second to tuple or "b".

added = len(b) > len(a)
changed = b[:len(a)] != a
both = added and changed

You could compare if len(b) > len(b) to check if an element was added or not, and if False , then compare if a==b or not.

if len(b) > len(a):
    if b[:len(a)] == a:
        print 'Added only'
    else:
        print 'Added and changed'
else:
    if b != a:
        print 'Changed'
    else:
        print 'No changes'

List is a mutable sequence , when comparing lists, it won't actually compare it's contents.

However, tuple, is immutable. comparing tuples will give you expected behavior in your case.

tuple(a) == tuple(b)

It's a simple way to test whether a == b.

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