2016-12-04 20 views
-4

2つの整数の配列 "current"と "target"を取り、追加リストと削除リストを表す2つの配列を生成して、 "current"配列は "target"配列を生成します。Python配列差分

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

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

出力は次のようになります:

additions: [2, 7] 

deletions: [3, 6, 8] 

以下が真であるように:

電流([1、以下 入力所与例えば

、 ([2,7]) - 削除([3,6,8])=ターゲット([1,2,5,7,9])

ソリューション:1が理解しやすいはずです以下

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

# 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

申し訳ありません - それは多かれ少なかれ動作しますが、thryは私が一歩一度最終的なリストで順不同です –

答えて

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]