如何检查2D数组中的前一行?在Python中

问题描述 投票:0回答:1

假设我有一个包含以下内容的tsv文件(名为“ tsv-test.txt”):

5ig7    G   H   0   I
5ig7    A   B   0   C
5ig7    D   E   0   F
5ig7    J   K   0   L
6ch8    D   E   0   B

在第一列中,我想检查上一行是否具有相同的术语。我已经将tsv作为2D数组读入列表。如何遍历2D数组在每一行进行此检查?供参考,这是我到目前为止所做的:

import csv

#read the tsv into python, tell python its a tsv
tsv_file = open("tsv-test.txt")
read_tsv = csv.reader(tsv_file, delimiter="\t")

#put tsv into a 2D array
arraytest = []
for line in read_tsv:
    arraytest.append(line)
python csv if-statement multidimensional-array
1个回答
0
投票

添加一个存储先前值的新变量,然后简单地对该变量执行检查

import csv

#read the tsv into python, tell python its a tsv
tsv_file = open("tsv-test.txt")
read_tsv = csv.reader(tsv_file, delimiter="\t")

#put tsv into a 2D array
arraytest = []
prev_row = ''
for line in read_tsv:
    if line[0] == prev_row
        arraytest.append(line)
    prev_row = line[0]
© www.soinside.com 2019 - 2024. All rights reserved.