在列表1中找到也在列表2中找到的项目

时间:2018-07-05 13:29:38

标签: python

我正在尝试从list1中查找与list2也匹配的元素。

到目前为止我所做的:

    with open('C:\python\list1.txt') as f:
    firstList = f.read().splitlines()

with open('C:\python\list2.txt') as g:
    secondList = g.read().splitlines()

resListFound = []
resListNotFound = []

for x in firstList:
    if x in secondList:
        resListFound.append(x)
        print (x + " found in list 2!")
    else:
        print (x + " NOT found in list 2")

    resListNotFound.append(x)


resultFile1 = open('found.txt', 'w')
resultFile2 = open('notFound.txt', 'w')

for item in resListFound:
    resultFile.write("%s\n" % item)
for item in resListNotFound:
    resultFile.write("%s\n" % item)

问题是我在第4行上收到OSErrror(22, 'Invalid Argument),但我看不到任何可能触发此事件的东西,因为它正在加载list2文件,就像list1

1 个答案:

答案 0 :(得分:4)

如果您不想维护订单,则可以使用一组进行快速比较:

with open('C:\python\list1.txt') as f:
    firstSet = set(f)

with open('C:\python\list2.txt') as g:
    secondSet = set(g)

resListFound = firstSet & secondSet
resListNotFound = firstSet - secondSet

如果您确实需要订购,则可以将第二个列表仅转换为一组以进行更快的查找:

secondSet = set(secondList)

for x in firstList:
    if x in secondSet:
        resListFound.append(x)
        print (x + " found in list 2!")
    else:
        resListNotFound.append(x)
        print (x + " NOT found in list 2")