如何摆脱for循环中的重复

时间:2014-03-31 16:42:38

标签: python for-loop iteration

for line in file2.splitlines():
  for l in file1.splitlines():
    if line in l:
     print l

我怎样才能摆脱重复?

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您需要打印重复项。

你可以这样做:

print [line for line in file2.splitlines() if line in file1.splitlines()]

但是如果你想以更好的方式做到这一点,请使用sets:

print list(file2.splitlines() & file1.splitlines())

答案 1 :(得分:0)

在第二个文件中创建一个字典,这将是一个更快的解决方案,它也将摆脱重复:

from collections import defaultdict

second_file = open('second.txt')
second_file_dict = defaultdict(int)
first_file_dict = defaultdict(int)

for line in second_file:
    second_file_dict[line.strip()] += 1
second_file.close()

first_file = open('first.txt')
for line in first_file:
    if line in second_file_dict and not in first_file_dict:
        print line
    first_file_dict[line.strip()] += 1        
first_file.close()