创建一个比较两个列表的程序

时间:2016-06-28 14:54:22

标签: python arrays if-statement

我正在尝试创建一个程序来检查一个列表中的项目是否不在另一个列表中。它保持返回行说明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

2 个答案:

答案 0 :(得分:3)

而不是列表,将文件作为集读取:

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次出现的情况,则应使用Counter中的collections

答案 1 :(得分: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
相关问题