使用 Chquopy 从 Python 返回多个列表给 Java。

huangapple go评论75阅读模式
英文:

Returning multiple lists from Python to Java using Chaquopy

问题

Python:

import random

def calculations():
    res1 = [33, 13, 20, 34]
    list = [1, 3, 5, 7]
    res2 = random.choices(list, k=10000)
    return res1, res2

Java:

if (!Python.isStarted())
    Python.start(new AndroidPlatform(getActivity()));

Python py = Python.getInstance();

PyObject obj = py.getModule("main").callAttr("calculations");

// How to extract the different objects from obj? Tried the following without success.
List<PyObject> totList = obj.asList();
int[] data3 = obj.toJava(int[].class);
英文:

How can I return multiple lists, values etc from my Python script to Java without ending up with a single object? Right now I end with a single PyObject with both returned values in it, and I haven't figured out how to divide them up again in Java.

Python:

import random

def calculations():

    res1 = [33, 13, 20, 34]

    list = [1,3,5,7]
    res2 = random.choices(list, k=10000)

    return res1, res2

Java:

if(!Python.isStarted())
            Python.start(new AndroidPlatform(getActivity()));

Python py = Python.getInstance();


PyObject obj = py.getModule(&quot;main&quot;).callAttr(&quot;calculations&quot;);

# How to extract the different objects from obj? Tried the following without success. 
List&lt;PyObject&gt; totList = obj.call(0).asList();
int[] data3 = obj.call(1).toJava(int[].class);

答案1

得分: 4

正如文档所述,call 相当于 Python 的 () 语法。但是元组(即 calculations 返回的类型)是不可调用的,所以我猜这可能是你收到的错误。

相反,你应该像这样做:

List<PyObject> obj = py.getModule("main").callAttr("calculations").asList();
int[] res1 = obj.get(0).toJava(int[].class);
int[] res2 = obj.get(1).toJava(int[].class);
英文:

As the documentation says, call is equivalent to Python () syntax. But a tuple (which is what calculations returns) is not callable, so I assume that's the error you're receiving.

Instead, you should do something like this:

List&lt;PyObject&gt; obj = py.getModule(&quot;main&quot;).callAttr(&quot;calculations&quot;).asList();
int[] res1 = obj.get(0).toJava(int[].class);
int[] res2 = obj.get(1).toJava(int[].class);

huangapple
  • 本文由 发表于 2020年9月18日 16:43:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/63952293.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定