简体   繁体   English

将一列中的所有值与 CSV Python 中的另一列进行比较

[英]Compare all values in a column with another column in CSV Python

I am trying to compare a CSV file of 2 columns with 1st column having 1500 values and 2nd column having 900.我正在尝试将 2 列的 CSV 文件与具有 1500 个值的第一列和具有 900 个值的第二列进行比较。

Example:例子:

ValueA ValueB
ValueB ValueC
ValueD ValueA
Valuec ValueD
ValueF
ValueG
ValueH
ValueZ

The output logic is Take a value from 1st column and compare it with all values in 2nd column:输出逻辑是从第一列取一个值并将其与第二列中的所有值进行比较:

  1. If there is a match, do nothing如果有匹配,则什么都不做
  2. If there is no match, output that Value to a file named results.csv如果不匹配,则将该值输出到名为 results.csv 的文件中

I am very new to programming and I have been looking at sites for this specific logic but failed to find.我对编程很陌生,我一直在寻找这个特定逻辑的网站,但没有找到。

Really appreciate any help on this.真的很感谢这方面的任何帮助。 Thanks in advance.提前致谢。

First, the best thing to do would be to load everything into two different arrays using the inbuilt Python CSV library, like so:首先,最好的做法是使用内置的 Python CSV 库将所有​​内容加载到两个不同的数组中,如下所示:

import csv
leftCol = []
rightCol = []
with open('example.csv') as csvFile:
    reader = csv.reader(csvFile)
    for row in reader:
        if len(row) > 0:
            leftCol.append(row[0])
        if len(row) > 1:
            rightCol.append(row[1])

You then have the two columns stored in nice arrays, leftCol and rightCol.然后,您将两列存储在漂亮的数组 leftCol 和 rightCol 中。 Then to compare them:然后比较它们:

 for leftItem in leftCol:
      for rightItem in rightCol:
          if leftItem != rightItem:
              print(leftItem)

In this case it just prints it, but you can swap the print for a file write or something else.在这种情况下,它只是打印它,但您可以将打印交换为文件写入或其他内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM