我正在尝试编写一个 python (2.7) 脚本来将多个 CSV 列表添加在一起(简单追加),但不添加文件 X 中与文件 Y 共享元素(第一列除外)的任何行。这是我的试用脚本:
import csv
import glob
with open('merged.csv','wb') as out:
seen = set()
output = []
out_writer = csv.writer(out)
csv_files = glob.glob('*.csv')
for filename in csv_files:
with open(filename, 'rb') as ifile:
read = csv.reader(ifile)
for row in read:
if {row[1] not in seen} & {row[2] not in seen} & {row[3] not in seen}:
seen.add(row[1])
seen.add(row[2])
seen.add(row[3])
output.append(row)
out_writer.writerows(output)
我确信这可以清理一些,但这是试运行 - 为什么它不能正确地将第 2、3 和 4 列中的元素添加到可见集合中,然后如果它们出现在所考虑的行?除了正确检查重复之外,它还成功输出了合并文件。 (如果合并的文件已经存在于目录中,这也可以工作吗?或者我会遇到麻烦吗?)
提前非常感谢! :)
最佳答案
我怀疑这条线没有达到你想要的效果:
if {row[1] not in seen} & {row[2] not in seen} & {row[3] not in seen}:
这是一个集合交集。演示:
>>> {False} & {True}
set([])
>>> {True} & {True}
set([True])
>>> {False} & {False}
set([False])
>>> bool(set([False]))
True #non-empty set is True in boolean context
也许你有意
if row[1] not in seen and row[2] not in seen and row[3] not in seen:
或(几乎*)等效
if all(value not in seen for value in row[1:4]):
(*) 如果行中的值较少,这不会引发异常
关于python - 将 CSV 文件与 Python 组合,不包含重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19510165/