代码之家  ›  专栏  ›  技术社区  ›  Darius Kucinskas

Jython(传递浮点数组到Java)有更多的python方式吗?

  •  1
  • Darius Kucinskas  · 技术社区  · 17 年前

    我正在用EclipseSWT/JFace编写Jython应用程序。我必须将浮点数组传递给Java对象,以从中返回一些值。我用的是jarray软件包。有更多的蟒蛇式的方法吗?

    bounds = zeros(4, 'f')
    # from java org.eclipse.swt.graphics.Path.getBounds(float[] bounds)
    path.getBounds(bounds)
    # from java org.eclipse.swt.graphics.Rectangle(int x, int y, int width,int height)
    rect = Rectangle(int(round(bounds[0])), 
                         int(round(bounds[1])),
                         int(round(bounds[2])),
                         int(round(bounds[3])))
    
    3 回复  |  直到 17 年前
        1
  •  4
  •   Aaron Digulla    17 年前

    也许吧。首先,您可以稍微减少代码:

    bounds = map(lambda v: int(round(v)), bounds)
    

    这样可以避免重复的投射。我的下一步将是创建一个助手方法来将数组转换为 Rectangle ,因此您不必重复此代码:

    def toRectangle(bounds):
        bounds = map(lambda v: int(round(v)), bounds)
        return Rectangle(bounds[0], bounds[1], bounds[2], bounds[3])
    

    这会给你留下:

    rect = toRectangle(path.getBounds(zeroes(4, 'f'))
    

    或者,创建一个直接接受路径的助手函数。

    或者你可以猴子补丁路径:

    def helper(self):
        bounds = zeros(4, 'f')
        self.getBounds(bounds)
        bounds = map(lambda v: int(round(v)), bounds)
        return Rectangle(bounds[0], bounds[1], bounds[2], bounds[3])
    
    org.eclipse.swt.graphics.Path.toRectangle = helper
    
    rect = path.toRectangle()
    

    请注意,这可能有点错误。如果不起作用,看看 classmethod() new.instancemethod() 关于如何在运行中向类添加方法。

        2
  •  4
  •   Frank Wierzbicki    17 年前

    如今,使用清单理解被认为更像是蟒蛇:

    rounded = [int(round(x)) for x in bounds]
    

    这将给您一个四舍五入整数的列表。当然,您可以将此分配给边界,而不是使用“Rounded”

    bounds = [int(round(x)) for x in bounds]
    

    在我们的邮件列表上,Charlie Groves指出,整个事情可以像这样由*操作员分解:

    rect = Rectangle(*[int(round(x)) for x in bounds])
    
        3
  •  2
  •   Charlie Groves    17 年前

    同样值得指出的是,不需要使用零来创建数组。只需使用包含可转换为正确类型的实例的python iterable调用getbounds:

    path.getBounds([0, 0, 0, 0])