简体   繁体   English

列出一级“拆包”

[英]List one level “unpacking”

I have a function which returns Sympy points:我有一个返回 Sympy 点的 function:

result = [Point3D(500, 500, 10), Point3D(-500, 500, 10), Point3D(-500, -500, 10), Point3D(500, -500, 10)]

But I need to get the values of the point, not the point instance, so I do this:但我需要获取点的值,而不是点实例,所以我这样做:

a, b, c, d = [], [], [], []
for i in range(3):
    a.append(result[0][i])
for i in range(3):
    b.append(result[1][i])
for i in range(3):
    c.append(result[2][i])
for i in range(3):
    d.append(result[3][i])

# And then pack it:
result = [tuple(a), tuple(b), tuple(c), tuple(d)]

I know this is a horrible way of getting the desired input, which is:我知道这是获得所需输入的一种可怕方式,即:

result = [(500, 500, 10), (-500, 500, 10), (-500, -500, 10), (500, -500, 10)]

How can I do it in a better way?我怎样才能以更好的方式做到这一点?

Use a list comprehension:使用列表推导:

result = [tuple([p[0], p[1], p[2]]) for p in result]

I just checked the documentation of Point3D , and it seems you can have a more elegant solution:我刚刚检查了Point3D的文档,看来您可以有一个更优雅的解决方案:

result = [tuple([p.x, p.y, p.z]) for p in result]

Or as @OscarBenjamin has indicated in the comments, which probably is the simplest solution, you can use:或者正如@OscarBenjamin 在评论中指出的那样,这可能是最简单的解决方案,您可以使用:

result = [p.args for p in result]

Small note: A new method has been added (by me) to sympy's point class which returns all the coordinates of the point:小提示:(由我)向 sympy 的点 class 添加了一个新方法,该方法返回该点的所有坐标:

result = [p.coordinates for p in result]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM