简体   繁体   中英

python compare difference between two lists

I have two lists like this:

newList = (
    (1546, 'John'),
    (8794, 'Michael'),
    (892416, 'Dave'),
    (456789, 'Lucy'),
    )

oldList = (
    (1546, 'John'),
    (8794, 'Michael'),
    (892416, 'Dave'),
    (246456, 'Alexander')
    )

I would like to have a function comparing both lists. It would be something like this:

def compare(new, old):
    print('Alexander is not anymore in the new list !')
    print('Lucy is new !')
    return newList 

I would like to compare with id of every person which is unique.

Edit: The result would be my function compare. It prints the difference. I don't know how to start

You can convert your lists into sets and take the differences

n = set(l[1] for l in newList)
o = set(l[1] for l in oldList)
print n - o # set(['Lucy'])
print o - n # set(['Alexander'])

edit: I wrote this before I know a lot about sets. Now I would recommend the solution using sets given below.

One solution:

removed = [o for o in old if o[0] not in [n[0] for n in new]]
added = [n for n in new if n[0] not in [o[0] for o in old]]

Or if you present your data as dictionaries:

old = dict(old) # if you do go for this approach be sure to build these
new = dict(new) # variables as dictionaries, not convert them each time

removed = {k:old[k] for k in old.keys() - new.keys()}
added = {k:new[k] for k in new.keys() - old.keys()}

Both turned into functions, returning items in ys but not in xs :

def tuple_list_additions(xs,ys):
  return [y for y in ys if y[0] not in [x[0] for x in xs]]

def dict_additions(xs,ys):
  return {k:ys[k] for k in ys.keys() - xs.keys()}

You can use set :

def compare(old, new):
    oldSet = set(old)
    newSet = set(new)
    removedElements =  oldSet - newSet
    newElements = newSet - oldSet
    for element in removedElements:
        print(element[1] + " is not anymore in the new list!")
    for element in newElements:
        print(element[1] + " is new!")

It's method which compares whole elements (id, name), so if you want to compare only id you should do some modifications (and for example use dicts).

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