【问题标题】:Combining CSV files with Python without repeat elements将 CSV 文件与 Python 相结合,没有重复元素
【发布时间】:2013-10-22 06:07:35
【问题描述】:

我正在尝试编写一个 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 列中的元素添加到看到的集合中,然后如果它们出现在行中则不附加行考虑的行?除了正确检查重复之外,它还成功输出了合并文件。 (如果合并的文件已经存在于目录中,这是否也有效,或者我会遇到麻烦?)

提前非常感谢! :)

【问题讨论】:

    标签: python csv glob


    【解决方案1】:

    我怀疑这条线不符合您的要求:

    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]):
    

    (*) 如果行中的值较少,这不会引发异常

    【讨论】:

      猜你喜欢
      • 2012-01-14
      • 2017-11-24
      • 2021-07-27
      • 1970-01-01
      • 2019-04-07
      • 2021-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多