2016-06-28 57 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