praneethng praneethng - 11 days ago 7
Python Question

python script to find the unique value

I have a script to find the unique value from 2 files

1.csv


11 12 13 14
21 22 23 24
11 32 33 34


2.csv


41 42 43 44 45
51 52 53 54 55
41 62 63 64 65


script is:

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


Usage:

$ python 1.py 1.csv 2.csv


output is

['51', '21']


but i want the output in different row like

51
21

Answer

Replace the last line by the following:

for result, count in counts.items():
    if count == 1:
        print(result)

It's not the most concise way to do it but at least it's quite readable

Comments