Why does my information extraction Python code get wrong output? -


i have csv file , want extract statistical information,so write code output total number of each activities each user id,but code output first id's information correctly.could tell me what's wrong code?here's code , wrong output.thank you.

from collections import counter import csv reader=csv.reader(file('f:\\hjzl\pythondata\log_train.csv','rb')) #read csv file  list1=[]     #create empty list def static(i):   #information extraction function   line in reader:        if line[0]==str(i):            list1.append(line[3])  #add activities list   print 'id:',i,counter(list1)  #print statistical information of id   list1[:]=[]                    #clear list   return list1  i=1 while i<4:                      #get statistical information of id1 id3     static(i)     i=i+1 print 'end' 

why information of id2 , id3 empty?

csv.reader() objects read data underlying file object, , file objects have file positions move start end read. if want read again need rewind file pointer start:

with open('f:\\hjzl\pythondata\log_train.csv','rb') csvfile:     reader = csv.reader(csvfile)      # ...      while < 4:         static(i)         csvfile.seek(0)         += 1 

however, better retrieve information file once. transpose columns:

with open('f:\\hjzl\pythondata\log_train.csv','rb') csvfile:     reader = csv.reader(csvfile)     columns = zip(*reader)  i, col in enumerate(columns[1:4]):     print 'id:', i, counter(col) 

Comments