簡體   English   中英

Python CSV閱讀器-比較一列中的每一行和每一行

[英]Python CSV Reader - Compare Each Row with Each Other Row Within One Column

我想將CSV文件的每一行與其自身以及一列中的每一行進行比較。
例如,如果列值是這樣的:

值_1
值_2
值_3

該代碼應選擇Value_1,並將其與Value_1(是,也與自身)進行比較,然后將Value_2與Value_3進行比較。 然后,它應該選擇Value_2,並將其與Value_1,Value_2,Value_3等進行比較。

為此,我編寫了以下代碼:

csvfile = "c:\temp\temp.csv"
with open(csvfile, newline='') as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        for compare_row in reader:
            if row == compare_row
                print(row,'is equal to',compare_row)
            else:
                print(row,'is not equal to',compare_row)

該代碼提供以下輸出:

['Value_1'] is not equal to ['Value_2']
['Value_1'] is not equal to ['Value_3']

該代碼將Value_1與Value_2和Value_3進行比較,然后停止。 循環1不會選擇Value_2和Value_3。 簡而言之,第一個循環似乎在停止之前僅對CSV文件的第一行進行迭代。

另外,我無法使用此代碼將Value_1與自身進行比較。 對解決方案有什么建議嗎?

我建議將CSV加載到內存中,但是考慮到大小,這不是一個選擇。

而是將其視為SQL語句,對於左表中的每一行,您都希望將其與右表中的值進行匹配。 因此,您將只掃描左側表格一次,然后開始重新掃描右側表格,直到左側達到EoF。

with open(csvfile, newline='') as f_left:
    reader_left = csv.reader(f_left, delimiter=',')
    with open(csvfile, newline='') as f_right:
        reader_right = csv.reader(f_right, delimiter=',')
        for row in reader_left:
            for compare_row in reader_right:
                if row == compare_row:
                    print(row,'is equal to',compare_row)
                else:
                    print(row,'is not equal to',compare_row)
            f_right.seek(0)

嘗試使用來自Python的內置包: Itertools

from itertools import product

with open("abcTest.txt") as inputFile:
    aList = inputFile.read().split("\n")
    aProduct = product(aList,aList)
    for aElem,bElem in aProduct:
        if aElem == bElem:
            print aElem,'is equal to',bElem
        else:
            print aElem,'is not equal to',bElem

您面臨的問題在Python中稱為笛卡爾積,我們需要將數據行與其自身以及每隔一行進行比較。

為此,如果您要多次讀取源文件,那么如果文件很大,則會導致明顯的性能問題。 取而代之的是,您可以將數據存儲在列表中,並在多個時間進行迭代,但這也將帶來巨大的性能開銷。

在這種情況下,itertool軟件包非常有用,因為它針對此類問題進行了優化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM