我有三个文本文件:
文件A:
13 abc
123 def
234 ghi
1234 jkl
12 mno
文件B:
^{pr2}$文件编号:
12 abc
34 sdg
43 yui
54 poi
54 def
我想看看第2列中的所有值在文件之间是匹配的。如果第二列已经排序,下面的代码可以工作。但是如果第二列没有排序,我如何排序第二列并比较文件?在
fileA = open("A.txt",'r')
fileB = open("B.txt",'r')
fileC = open("C.txt",'r')
listA1 = []
for line1 in fileA:
listA = line1.split('\t')
listA1.append(listA)
listB1 = []
for line1 in fileB:
listB = line1.split('\t')
listB1.append(listB)
listC1 = []
for line1 in fileC:
listC = line1.split('\t')
listC1.append(listC)
for key1 in listA1:
for key2 in listB1:
for key3 in listC1:
if key1[1] == key2[1] and key2[1] == key3[1] and key3[1] == key1[1]:
print "Common between three files:",key1[1]
print "Common between file1 and file2 files:"
for key1 in listA1:
for key2 in listB1:
if key1[1] == key2[1]:
print key1[1]
print "Common between file1 and file3 files:"
for key1 in listA1:
for key2 in listC1:
if key1[1] == key2[1]:
print key1[1]
如果只想按第二列对}进行排序,这很简单:
A1
、B1
、和{如果你不明白
^{pr2}$itemgetter
,这是相同的:但是,我认为更好的解决方案是使用
set
:或者,更简单地说,不要首先构建列表;请执行以下操作:
任何一种方式:
为了进一步简化,您可能需要首先将重复的内容重构为函数:
然后你就能找到更多的机会。例如:
正如John Clements所指出的,你甚至不需要所有三个都是集合,只要A1,所以你可以这样做:
^{8}$您需要做的唯一其他更改是必须调用
intersection
,而不是使用&
运算符,因此:我不确定最后的改变是否真的是一种进步。但是在Python3.3中,您只需要将
return set(…)
改为yield from (…)
,我可能会用这种方式来实现。(即使文件非常大并且有大量的重复项,因此会有性能上的损失,我只需要在itertools
调用周围粘贴itertools
中的unique_everseen
。)相关问题 更多 >
编程相关推荐