我有一个脚本可以从2个文件中找到唯一值
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))
编辑:
在您的代码中(实际上是我昨天给您的答案),请执行以下操作:
print("\n".join([i for i, c in counts.items() if c == 1]))
答案 1 :(得分:0)
用以下内容替换最后一行:
for result, count in counts.items():
if count == 1:
print(result)
这不是最简洁的方法,但至少它是可读的