如果我只有四行,为什么python会打印多行?

时间:2017-03-18 13:41:44

标签: python

我希望有人可以帮助这个循环。 我有以下CSV文件:

143560,00210,318,2,2,TRS,
143493,00210,309,6,4,TRS,             
143494,00210,309,6,4,TRS,             
143495,00210,309,10,6,TRS,

我想要完成的是在变量中加载每一列并逐行比较TOTS和UNS列,然后逐行打印剩余的变量。

例如,在第四栏中,评估如下: 如果10不相等6打印143495 00210 309 TRS。我已经导入了CSV并设法将每个列放在一个变量中,但是当我进行评估时,由于某些未知的原因,Python在移动到另一行之前多次打印同一行(准确地说是5或6次)。

有没有办法在不打印其他行的情况下对此进行评估?

import csv
import os
dir = "C:/Users/Hande/Desktop/try"
os.chdir(dir)
with open('pyton.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')

#VARIABLE DECLARATION 
DOCS    = []
COS     = []
MICS    = []
TOTS    = []
UNS     = []
LOC_FRS = []
LOC_TOS = []

for row in readCSV:
#SETS EACH COLUNM TO AN ARRAY INDEX 
    DOC    = row[0]
    CO     = row[1]
    MIC    = row[2]
    TOT    = row[3]
    UN     = row[4]
    LOC_FR = row[5]


#APPENDS THE DATA 
    DOCS.append(DOC)
    COS.append(CO)
    MICS.append(MIC)
    TOTS.append(TOT)
    UNS.append(UN)
    LOC_FRS.append(LOC_FR)

for D in DOCS:
  for C in COS:
    for M in MICS:
      for T in TOTS:
        for U in UNS:
          for LF in LOC_FRS:
            for a, b, c, d, e, f in zip(D, C, M, T, U, LF): 
              if d != e: 
                print (D, C, M, LF)
              else:  
                print("good")

2 个答案:

答案 0 :(得分:0)

我不完全确定你要做什么,但这也可能有助于并从评论中回答你的问题。

我已将您的数据格式化为&像你的例子一样将它保存到Python.csv中:

143560,00210,318,2,2,'TRS'
143493,00210,309,6,4,'TRS'
143494,00210,309,6,4,'TRS'
143495,00210,309,10,6,'TRS'

然后,您可以将其读入熊猫并轻松处理

import pandas

#read the csv into a pandas Data.Frame
with open('python.csv', 'r') as csvfile:
    spreadsheet= pandas.read_csv(csvfile, names = ['DOCS','COS','MICS','TOTS','UNS', 'LOC_FRS'])

#now you can print rows of the spreadsheet like so
#e.g. if you want to get rows where TOTS is 6 as in your comment
print spreadsheet[spreadsheet['TOTS']==6]

您可以更全面地了解此索引的工作原理here

答案 1 :(得分:0)

根据您的输入,这将读取每一行并将第3列与第4列进行比较,仅打印它们不匹配的行。

import csv
import sys

with open('python.csv') as csvfile:
    reader = csv.reader(csvfile)
    writer = csv.writer(sys.stdout)
    for line in reader:
        docs,co,mic,tot,un,loc_fr,_ = line
        if int(tot) != int(un):
            writer.writerow([docs,co,mic,loc_fr])

输出:

143493,00210,309,TRS
143494,00210,309,TRS
143495,00210,309,TRS