Python 2.7 在列表列表中查找最小值、最大值 [英] Python 2.7 find min,max on list of lists

查看:58
本文介绍了Python 2.7 在列表列表中查找最小值、最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 的菜鸟,来自 C/C++.我正在使用连接到 Beaglebone Black 的加速度计.我从加速度计收集了 6 个 [X,Y,Z] 读数:

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

我需要从这组六个读数中找到 XYZ 的最小值和最大值.我的代码是:

max = [0] * 3分钟 = [0] * 3对于 ndx,enumerate(calib) 中的样本:x, y, z = 校准 [ndx]如果 x >最大值[0]:最大值[0] = x如果 x <分钟[0]:分钟[0] = x如果 y >最大值[1]:最大值[1] = y如果y<分钟[1]:分钟[1] = y如果 z >最大值[2]:最大值[2] = z如果z<分钟[2]:分钟[2] = z打印分钟",分钟分钟 [-1513, -1673, -623]打印最大",最大最大 [1350, 1464, 1564]

这似乎有效,但看起来不像pythonic".必须有一种更清洁的方法来做到这一点.有什么建议吗?

解决方案

首先,重新映射列表,为您提供 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)]

这篇关于Python 2.7 在列表列表中查找最小值、最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆