2016-11-24 68 views
-1

我有一個腳本,從2檔python腳本找出獨特的價值

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 

腳本是找到獨特的價值:

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

用法:

$ python 1.py 1.csv 2.csv 

輸出

['51', '21'] 

,但我想不同的行輸出像

51 
21 

回答

0

由以下替換最後一行這不是最簡潔的方式,但至少它很可讀

1

使用string.join加入一個\n列表項:

l = ['51', '21'] 
print("\n".join(l)) 

編輯:

在你的代碼(這實際上是一個答案,我昨天給你),這樣做:

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

print("\n".join([i for i, c in counts.items() if c == 1])) 
+0

我該如何在代碼中實現這一點? – praneethng

+0

謝謝你 – praneethng