Reputation: 11367
I am using web.py for managing my web application and using MySQL as the database. I make a raw query and get the results and i convert it to a list and iterate over it. I need to push the retrieved columns in Arrays (or Numpy arrays) and then plot using Matplotlib. Everything works but i am not sure if the approach i use is most efficient? The code is:
retrieved_data=list(db.query(query))
LEN=len(retrieved_data)
x=[0]*LEN
y=[0]*LEN
X=[None]*LEN
for i in range(0,LEN):
x[i]=retrieved_data[i]["timestamp"]
y[i]=retrieved_data[i][parameter]
X[i]=datetime.datetime.fromtimestamp(x[i],pytz.timezone(TIMEZONE))
Upvotes: 1
Views: 392
Reputation: 4479
You don't have to convert the result of db.query if you only need to iterate it once. So your particular example can be a little bit simplified.
x, y, X = [], [], []
for item in db.query(query):
x.append(item.timestamp)
y.append(item[parameter])
X.append(datetime.datetime.fromtimestamp(item.timestamp,
pytz.timezone(TIMEZONE))
Or if you need to iterate many times on the same result, you may use .list()
method to convert it into list.
retrieved_data = db.query(query).list()
Upvotes: 2