2

I'm a noob to Python, coming from C/C++. I'm working with an accelerometer connected to a Beaglebone Black. I collect 6 [X,Y,Z] readings from the accelerometer as:

calib = [[-72, -80, -673], [-31, -1673, 481], [-29, -62, 1564], [-148, 1464, 545], [-1513, -67, 539], [1350, -80, 480]]

I need to find the min and max for X, Y, and Z from this set of six readings. The code I have is:

max = [0] * 3
min = [0] * 3

for ndx, sample in enumerate(calib):
    x, y, z = calib[ndx]
    if x > max[0]:
        max[0] = x
    if x < min[0]:
        min[0] = x
    if y > max[1]:
        max[1] = y
    if y < min[1]:
        min[1] = y
    if z > max[2]:
        max[2] = z
    if z < min[2]:
        min[2] = z

print "min", min
min [-1513, -1673, -623]

print "max", max
max [1350, 1464, 1564]

This seems to work, but just doesn't look "pythonic". There has to be a cleaner way to do this. Any advice?

Totem
  • 7,189
  • 5
  • 39
  • 66
RayZ
  • 29
  • 1
  • 1
  • 4
  • You could just sort the measurements and take the first 3, like this: `listOfNumbers.sort()[:3]`. You can get the last three elements of a list by `someList[-3:]`. But I'd recommend using `numpy` for speed if you're dealing with numbers. – Aleksander Lidtke Feb 07 '14 at 22:55
  • @AleksanderLidtke, that doesn't solve the independent x, y, and z problems – mhlester Feb 07 '14 at 23:01
  • You need to have a custom criterion for sorting according to 3 criteria. – Aleksander Lidtke Feb 08 '14 at 17:01
  • A big THANKS to those who pointed me to the existing answer, and @mhlester who wrote a similar solution below. You guys rock! – RayZ Feb 09 '14 at 21:25

1 Answers1

13

First, remap the list to give you a list of x, y, and z lists:

xyz = zip(*calib)

Then map min and max to the list:

>>> map(min, xyz)
[-1513, -1673, -673]

>>> map(max, xyz)
[1350, 1464, 1564]

Alternatively as one list comprehension:

>>> [(min(a), max(a)) for a in zip(*calib)]
[(-1513, 1350), (-1673, 1464), (-673, 1564)]
mhlester
  • 22,781
  • 10
  • 52
  • 75
  • 1
    I'd vote you up a tic for the list comprehension idea if it would let me. Thanks. – RayZ Feb 09 '14 at 21:27