for循环和嵌套for循环

时间:2014-03-31 01:01:53

标签: python

for file2.splitlines()中的行:   for file1.splitlines()中的l:     如果在l中行:      打印l

2 个答案:

答案 0 :(得分:1)

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

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()

答案 1 :(得分:1)

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