簡體   English   中英

python比較兩個列表之間的差異

[英]python compare difference between two lists

我有兩個這樣的清單:

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

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

我想有一個比較兩個列表的函數。 就像這樣:

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

我想與每個人的ID進行比較。

編輯:結果將是我的功能比較。 它打印出差異。 我不知道怎么開始

您可以將列表轉換成集合並進行區別

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'])

編輯:我寫這是在我不了解集合之前。 現在,我將建議使用下面給出的集合的解決方案。

一種解決方案:

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

或者,如果您將數據顯示為字典:

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()}

兩者都變成了函數,以ys返回項目,但沒有以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()}

您可以使用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!")

它是一種比較整個元素(id,name)的方法,因此,如果您只想比較id,則應該進行一些修改(例如使用dicts)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM