2017-09-26 96 views
1

我有兩個列表和b。我想提取相似和不相似的項目。事情是[i]在b [i]之內,例如[0] == b [0:3]。我在這裏嘗試的解決方案獲得類似的(在else語句中),但不是不相似的(如果語句)。 if語句會創建多個輸入,請指出我缺少的內容。提取內容的列表

a = [[1,2,3], [9,8,3], [1,3,5], [2,3,8], [0,3,5], [5,5,7]] 
b = [[1,2,3,4,5,6], [4,5,6,8,6,0], [9,8,3,7,8,9], [5,5,7,0,3,9]] 

temp, temp1 = [], [] 
for i in a: 
    for j in b: 
     if i != j[0:3]: 
      temp.append(j) 
     else: 
      temp1.append(j) 

#print temp should output [[1,3,5], [2,3,8], [0,3,5]] but it gives something different 

#print temp1 [[1, 2, 3, 4, 5, 6], [9, 8, 3, 7, 8, 9], [5, 5, 7, 0, 3, 9]] is fine 

回答

1

循環嵌套使if條件在所有可能的ai和bj組合上執行。此外,從你在你的要求中提到,你似乎需要在臨時AI值(未BJ)

您可以使用一個布爾變量保存找到/未找到布爾值,如圖所示:

a = [[1,2,3], [9,8,3], [1,3,5], [2,3,8], [0,3,5], [5,5,7]] 
b = [[1,2,3,4,5,6], [4,5,6,8,6,0], [9,8,3,7,8,9], [5,5,7,0,3,9]] 

temp, temp1 = [], [] 
for i in a: 
    found = False 
    for j in b: 
     if i != j[0:3]: 
      pass 
     else: 
      found = True 
      temp1.append(j) 
    if not found : 
     temp.append(i) 
0
a = [[1,2,3], [9,8,3], [1,3,5], [2,3,8], [0,3,5], [5,5,7]] 
b = [[1,2,3,4,5,6], [4,5,6,8,6,0], [9,8,3,7,8,9], [5,5,7,0,3,9]] 

temp, temp1 = [], [] 
for i in a: 
    for j in b: 
     if i != j[0:3]: 
      **temp.append(i) 
      break** 
     else: 
      temp1.append(j)