如何通过比较三个csv文件列表中的第一列来获取唯一值?

时间:2016-11-22 15:04:41

标签: python

每个文件中有两个文件。

导入csv

计数= {}

表示sys.argv [2:]:

with open(a) as c:

    # Read it as a CSV file.

    reader = csv.reader(c, delimiter=' ')

        count = counts.get(row[0], 0)

        counts[row[0]] = count + 2

print([i for i,c in counts.items()if c == 2])

1 个答案:

答案 0 :(得分:0)

你应该亲自尝试一下。但是假设你想要找到所有文件所特有的数字,这就可以了。

import csv
import sys

# Count all first-column numbers.
counts = {}

# Loop over all input files.
for a in sys.argv[1:]:

    # Open the file for reading.
    with open(a) as c:
        # Read it as a CSV file.
        reader = csv.reader(c, delimiter=' ')
        for row in reader:
            # Get the current count of the number in the first column.
            # Default is 0.
            count = counts.get(row[0], 0)
            # Increment the count by 1.
            counts[row[0]] = count + 1

# Print only those numbers that have a count of 1.
print([i for i, c in counts.items() if c == 1])

一样使用它
$ python3.5 so.py file1.csv file2.csv file3.csv

输出:

['22', '55']