Category Archives: Coding

Python tips – Simple sensor data handling 2

Last time, I described a simple way to take a series of data samples grouped by timestamp and reorganise them to group by the sensor from which they came. This time I will describe a simple way to read the data in from a file. Note that I will leave out error checking for the purpose of clarity, but this is always something which should be considered.

Continue reading

Python tips – Simple sensor data handling

Say you have a system which collects data from a group of sensors. Let’s have three sensors giving integer values for the sake of argument, but this doesn’t affect what I’m about to show you. The easiest way to store this data (assuming you want some history) is as a list of tuples, so if the data you get from the sensors is (1, 5, 3) at t=0, (2, 5, 3) at t=1, (2, 4, 4) at t=2, and (2, 5, 2) at t=3 then you would be storing

[(1, 5, 3), (2, 5, 3), (2, 4, 4), (2, 5, 2)]

Continue reading

Python tips – Reverse iteration

This post, the first in what will be a sporadic series, relates to a mistake I saw recently when looking at through some Python code. The author had used the following method to iterate backwards through a list:

for i in range(len(foo)):
    print foo[-i]

It wasn’t a print in the original, it was something else which would have been far harder to spot had it introduced subtle errors into the results of the code. Given Python’s ability to index from the end of a list using negative indices, this seems to be a suitable solution. The problem here is that foo[-0] isn’t the last item in the list, foo[-1] is. The correct code the author was looking for was:

for item in reversed(foo):
    print item

Or, if you need the index of the item as well:

for i,value in enumerate(reversed(foo)):
    print i,item