如何使用python获得ndimensional多维数据集中所有整数点的列表?

2024-05-29 02:55:54 发布

您现在位置:Python中文网/ 问答频道 /正文

给定一个坐标从(-x,-x,-x,…)到(+y,+y+y,…),x,y>;0的立方体,如何用简短易读的代码得到所有整数的列表?你知道吗

到目前为止,我已经:

list((x,y,z) for x in range(-x,y) for y in range(-x,y) for z in range(-x,y))
# has the dimension hardcoded

list(itertools.product(*[np.arange(-x, y)]*dim))
# difficult to understand what is going on

有没有更直观的解决方案?你知道吗


Tags: the代码ingt列表fornprange
2条回答

你的第二个解决方案看起来很好,不过我会这样做:

list(itertools.product(range(-x, y), repeat=dim))

只需将“硬编码”版本封装在函数中,并将维度作为参数传递

def cube_points(x1, x2, y1, y2, z1, z2): #This describes any rectangular prism
    return [(x,y,z) for x in range(x1, x2+1) for y in range(y1, y2+1) for z in range(z1, z2+1)]

其中x1x2是立方体投影到x轴上形成的直线的端点,等等

编辑:对于n维立方体

from itertools import product
def ndcube(*args): #accepts a list of 2-tuples
    return list(product(*map(lambda x: range(x[0], x[1]+1), args)))

相关问题 更多 >

    热门问题