I am trying to use python script in the Android studio using chaquopy. But I have 2 problems.
python random
.Here is the Python Script.
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}'
It is showing no module named random found.
And The activity file
private String getTeam() {
Python python = Python.getInstance();
PyObject file = python.getModule("getTeam");
return file.callAttr("getPlayers", wk, batsman, bowler, ar);
}
I am calling getTeam
method in onCreate
. So, How can I get the list of keys and values from python
script?
EDIT
I have used this code to access the data but It is showing com.chaquo.python.PyException: TypeError: jarray does not support slice syntax
.
Here is the Code
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.
I assume you're talking about an error shown in the Android Studio editor, rather than one which happened at runtime. As 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?
You can write the Python code like this:
return [f'{key}: {name}' for key in players for name in players[key]]
And the Java code like this:
file.callAttr("getPlayers", wk, batsman, bowler, ar).toJava(String[].class)
That will give you a Java String[]
array, which you can then process however you want.
EDIT for jarray does not support slice syntax
:
This issue is fixed in Chaquopy 9.0.0. With older versions, you can work around it by converting the array to a Python list
.
To convert in Python:
def getPlayers(wk, batsman, bowler, allRounder):
wk = list(wk)
batsman = list(batsman)
# etc.
Or to convert in Java:
PyObject list = python.getBuiltins().get("list");
return file.callAttr("getPlayers",
list.call(wk.toArray()),
list.call(batsman.toArray()),
// etc.