且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python 2.7 在列表列表中查找最小值、最大值

更新时间:2023-02-26 19:41:58

首先,重新映射列表,为您提供 xy 的列表z 列表:

xyz = zip(*calib)

然后将 min 和 max 映射到列表:

>>>地图(分钟,xyz)[-1513, -1673, -673]>>>地图(最大,xyz)[1350, 1464, 1564]

或者作为一个列表推导式:

>>>[(min(a), max(a)) for a in zip(*calib)][(-1513, 1350), (-1673, 1464), (-673, 1564)]

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?

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)]