英文:
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("main").callAttr("calculations");
# How to extract the different objects from obj? Tried the following without success.
List<PyObject> 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<PyObject> obj = py.getModule("main").callAttr("calculations").asList();
int[] res1 = obj.get(0).toJava(int[].class);
int[] res2 = obj.get(1).toJava(int[].class);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论