2016-12-04 46 views
-4

編寫一個函數或程序,它將採用2個整數「當前」和「目標」數組,並生成2個數組,表示添加列表和刪除列表,以便將添加和刪除應用於「當前「數組將產生」目標「數組。Python Array Diff

例如,給定以下 輸入:

current = [1, 3, 5, 6, 8, 9] 

target = [1, 2, 5, 7, 9] 

的輸出將是:

additions: [2, 7] 

deletions: [3, 6, 8] 

所以,以下爲真:

電流([1, (3,5,7,9)] +添加物([2,7]) - 刪除物([3,6,8])=目標物([1,2,5,7,9])

解決方案:

到目前爲止,我有這樣的:

--------------------------- 

# import array function 
from array import array 

# create an integer array named current 
current = array('i', [1, 3, 5, 6, 8, 9]) 

# add items from additions list into current array using the fromlist() method 
additions = [2, 7] 
current.fromlist(additions) 

# remove items on deletions list from current array using the.  remove() method 
current.remove(3) 
current.remove(6) 
current.remove(8) 

+1

什麼問題? – Dekel

+0

你能澄清「不起作用」嗎?你有錯誤嗎? – Dekel

+0

道歉 - 它或多或少的作品,但是,當我一步一步地進入最終名單時, –

回答

0

它會爲你工作...

def addlist(current,target): 
     add = [] 
     intersection = set(current) & set(target) 
     for i in target: 
       if i not in intersection: 
         add.append(i) 
     return add 

def removeList(current,target): 
     remove = [] 
     intersection = set(current) & set(target) 
     for i in current: 
       if i not in intersection: 
         remove.append(i) 
     return remove 

def main(): 
     current = [1, 3, 5, 6, 8, 9] 
     target = [1, 2, 5, 7, 9] 
     print(addlist(current,target)) 
     print(removeList(current,target)) 

if __name__=="__main__": 
     main() 
0

下面一個應該很容易理解。

>>> current = [1, 3, 5, 6, 8, 9] 
>>> target = [1, 2, 5, 7, 9] 
>>> set(current) & set(target) 
set([1, 5, 9]) 
>>> unique = list(set(current) & set(target)) 
>>> additions = [i for i in target if i not in unique] 
>>> additions 
[2, 7] 
>>> deletions = [i for i in current if i not in unique] 
>>> deletions 
[3, 6, 8] 
>>> 
0

這也能發揮作用。

current = [1, 3, 5, 6, 8, 9] 
target = [1, 2, 5, 7, 9] 
additions=[x for x in target if x not in current] 
deletions=[x for x in current if x not in target]