我绝对相信这个问题之前肯定已被多次询问,但对于我的生活,我找不到回答这个问题的主题:
我正在创建一个模型导出器,我希望通过遍历顶点列表并将最低和最高x,y和z值选入其自己的最小/最大元组来计算每个对象的最小和最大边界在同一表格上。我现在这样做的方式是这样的:
x = max(vertices,key=itemgetter(0))[0]
y = max(vertices,key=itemgetter(1))[1]
z = max(vertices,key=itemgetter(2))[2]
extents_max = (x, y, z)
x = min(vertices,key=itemgetter(0))[0]
y = min(vertices,key=itemgetter(1))[1]
z = min(vertices,key=itemgetter(2))[2]
extents_min = (x, y, z)
这样可行,但在python中有更优雅,单行的方式吗?
答案 0 :(得分:2)
只需删除重复的0,1,2,它就是一行:
extents_max = [max(vertices,key=itemgetter(i))[i] for i in range(3)]
如果您需要它来保持元组,如您在示例中所示:
extents_max = tuple(max(vertices,key=itemgetter(i))[i] for i in range(3))
答案 1 :(得分:1)
您可以使用序列解包来计算这些:
mins, maxs = zip(*[(min(map(itemgetter(i), vertices)),
max(map(itemgetter(i), vertices)))
for i in range(3)])
例如:
>>> vertices = [(1,4,2), (1,3,0), (4,2,5)]
>>> mins, maxs = zip(*[(min(map(itemgetter(i), vertices)),
... max(map(itemgetter(i), vertices)))
... for i in range(3)])
>>> mins
(1, 2, 0)
>>> maxs
(4, 4, 5)
答案 2 :(得分:0)
Demodata:
verts = [(-94, -24, -87), (90, 27, -56), (-22, -59, -44), (50, -70, 52),
(-31, 37, -24), (-73, 53, 66), (-47, -28, 99), (-3, -42, -66),
(2, 85, 58), (79, -86, 39)]
查找最小/最大:
z = [(min(l),max(l)) for l in zip(*verts)] # [(min,max) for each
# (x0,..,xn),(y0,..,yn),(z0,..,zn) ]
extends_min, extends_max = zip(*z)
print(extends_min, extends_max)
输出:
(-94, -86, -87) (90, 85, 99)