如何使用 chaquopy 在 Android 工作室中 运行 python 编写脚本?

How to run python script in Android studio using chaquopy?

我正在尝试使用 chaquopy 在 Android 工作室中使用 python 脚本。但是我有两个问题。

  1. 我无法导入 python random
  2. 如何检索列表。

这是 Python 脚本。

import random
def getPlayers(wk, batsman, bowler, allRounder):
    chosen = batsman[:3] + bowler[:3] + allRounder[:1] + wk[:1]
    remainder = batsman[3:] + bowler[3:] + allRounder[1:] + wk[1:]
    random.shuffle(remainder)
    chosen.extend(remainder[:3])

    players = {'Batsman': [x for x in chosen if x in batsman],
               'Bowler': [x for x in chosen if x in bowler],
               'AllRounder': [x for x in chosen if x in allRounder],
               'Wk': [x for x in chosen if x in wk]}

    for key in players:
        for name in players[key]:
            return f'{key}: {name}'

它显示没有找到名为 random 的模块。

和 activity 文件

 private String getTeam() {
    Python python = Python.getInstance();
    PyObject file = python.getModule("getTeam");
    return file.callAttr("getPlayers", wk, batsman, bowler, ar);
}

我正在 onCreate 中调用 getTeam 方法。那么,如何从 python 脚本中获取键和值的列表?

编辑

我已使用此代码访问数据,但它显示 com.chaquo.python.PyException: TypeError: jarray does not support slice syntax

这是代码

  String[] team = getTeam();
    for (String s : team) {
        Log.d("Player", s);
    }

}

private String[] getTeam() {
    Python python = Python.getInstance();
    PyObject file = python.getModule("getTeam");
    return file.callAttr("getPlayers", wk.toArray(), batsman.toArray(), bowler.toArray(), ar.toArray()).toJava(String[].class);
}

It is showing no module named random found.

我假设您是在谈论 Android Studio 编辑器中显示的错误,而不是在运行时发生的错误。作为 the documentation says, errors in the editor are harmless: just go ahead and run your app, and if there really is an error, the details will be displayed in the Logcat.

How can I get the list of keys and values from python script?

您可以这样编写 Python 代码:

return [f'{key}: {name}' for key in players for name in players[key]]

Java 代码如下:

file.callAttr("getPlayers", wk, batsman, bowler, ar).toJava(String[].class)

这将为您提供一个 Java String[] 数组,然后您可以根据需要对其进行处理。


编辑 jarray does not support slice syntax:

此问题已在 Chaquopy 9.0.0 中修复。对于旧版本,您可以通过将数组转换为 Python list 来解决此问题.

在Python中转换:

def getPlayers(wk, batsman, bowler, allRounder):
    wk = list(wk)
    batsman = list(batsman)
    # etc.

或在Java中转换:

PyObject list = python.getBuiltins().get("list");
return file.callAttr("getPlayers", 
                     list.call(wk.toArray()), 
                     list.call(batsman.toArray()), 
                     // etc.