2 回答
TA贡献1895条经验 获得超3个赞
只需将set()列表包裹起来。
def readfile(fn):
with open(fn, 'r') as fh:
return fh.read().splitlines()
diff = set(readfile("file1.txt")).difference(set(readfile("file2.txt")))
TA贡献1780条经验 获得超4个赞
您可以申请set将列表当场转换为集合。所以这就足够了:
a_file = open(r'c:\a.csv', 'r')
b_file = open(r'c:\b.csv', 'r')
a_set = set(a_file.readlines())
b_set = set(b_file.readlines())
a_file.close()
b_file.close()
difference_list = a_set.difference(b_set)
但我也建议应用with语句来执行基本的文件操作(打开、关闭等),并确保在几乎任何异常的情况下它们都将被正确关闭。在这种情况下,代码将如下所示:
with open(r'c:\a.csv', 'r') as a_file, open(r'c:\b.csv', 'r') as b_file:
a_set = set(a_file.readlines())
b_set = set(b_file.readlines())
difference_list = a_set.difference(b_set)
添加回答
举报
