2016-12-04 48 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]