I have a python question, but i think any programer would know enough to send me in the right direction.I have found some really good code for sorting data. Here is an example of one i want to use:
from operator import itemgetter, attrgetter
data = [('red', 1,80), ('blue', 1,900), ('red', 2,50), ('blue', 2,300)]
ss=sorted(data, key=itemgetter(0))
print ss
my problem is getting data in this specific format as above because i read my data in from a csv file and i can not type it in like the data is above, because i have data stored on files.
I read my data in to python like this:
reader = csv.reader(open("Meterdata2.csv","rb"));
name=[]; idc=[]; startD=[]; endD=[]; cons=[]; monthdays=[];
for row in reader:
if row[0] != 'IB_id':
name.append(str(row[1])) # name
idc.append(long(row[2])) # idc_acct
startD.append(tcnvrt.str2datetime(row[3]))
endD.append(tcnvrt.str2datetime(row[4]))
cons.append(int(row[6])) # consumption
monthdays.append((tcnvrt.str2datetime(row[4])-tcnvrt.str2datetime(row[3])).days)
IDC=array(idc); Name=array(name); STARTD=array(startD); # these are numpy.ndarray
END_D=array(endD); CONS=array(cons); MONTHDAYS=array(monthdays)
AA=[IDC,Name,STARTD,END_D,MONTHDAYS,CONS]
I want to sort my data by my endD variable wich is an array of dates.
I did find some functions online that i think might do the trick of getting data in the specific form to sort it,but i have not been able to figure it out. I keep writing up these function to apply to my example but i can not get them to work.
here are the function i think might work for this (if i change the variables):
def __init__(self, name, grade, age):
self.name = name
self.grade = grade
self.age = age
def __repr__(self):
return repr((self.name, self.grade, self.age))
can someone please push me in the right direction. Thank you
I think you just want to convert it into a list of tuples, before sorting, right? You can do this by using the zip function:
but I do not understand why you do not sort the rows as they are straight away…