我试图从 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)
问题是我正在OSErrror(22, 'Invalid Argument)
第 4 行,但我没有看到任何可能触发它的东西,因为它正在加载list2
文件,就像list1
如果您不想维护订单,您可以使用 set 进行更快的比较:
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")
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句