2016-06-28 58 views
0

我試圖創建一個程序來檢查一個列表中的項目是否不在另一個列表中。它不斷返回行說x值不在列表中。有什麼建議麼?對不起我的代碼,這是相當草率。創建一個比較兩個列表的程序

搜索在數組

文件把.TXT成陣列

with open('Barcodes', 'r') as f: 
    barcodes = [line.strip() for line in f] 

with open('EAN Staging', 'r') as f: 
    EAN_staging = [line.strip() for line in f] 

陣列

list1 = barcodes 
list2 = EAN_staging 

主代碼

fixed = -1 

for x in list1: 
    for variable in list1:             # Moves along each variable in the list, in turn 
     if list1[fixed] in list2:           # If the term is in the list, then 
      fixed = fixed + 1 
      location = list2.index(list1[fixed])       # Finds the term in the list 
      print() 
      print ("Found", variable ,"at location", location)    # Prints location of terms 
+0

所以你想知道哪些項目只在其中一個列表中? – DeepSpace

+2

什麼是第一個for list1循環中的x?似乎沒有任何意義。 –

+0

@DeepSpace不,我想檢查條形碼列表中的任何數據是否不在EAS登臺列表中。 – minidave2014

回答

3

取而代之的列表,閱讀文件, SE TS:

with open('Barcodes', 'r') as f: 
    barcodes = {line.strip() for line in f} 

with open('EAN Staging', 'r') as f: 
    EAN_staging = {line.strip() for line in f} 

然後,所有你需要做的是計算它們之間的對稱差:

diff = barcodes - EAN_staging # or barcodes.difference(EAN_stagin) 

提取例如:

a = {1, 2, 3} 
b = {3, 4, 5} 
print(a - b) 
>> {1, 2, 4, 5} # 1, 2 are in a but in b 

需要注意的是,如果你是集經營,元素出現次數的信息將會丟失。如果您關心的是barcodes中存在元素3次的情況,但EAN_staging中只有2次,則應使用collections中的Counter

0

你的代碼似乎不能完全回答你的問題。如果你想要做的就是看看哪些元素沒有共享,我認爲set是要走的路。

set1 = set(list1) 
set2 = set(list2) 
in_first_but_not_in_second = set1.difference(set2) # outputs a set 
not_in_both = set1.symmetric_difference(set2) # outputs a set