-
bennr01
I think you may be confusing a few different datatypes here, so I'll try to explain some approaches for your problem.
First of, Python does not really have something like arrays. Usually, when one wants to use something akin to an array in Python, one uses a
list
instead. The main difference between alist
and an array is that usually arrays are fixed size and often fixed type also while Python lists can have any required size and mixed types of elements. However, you wrote "same variables", so lists may not be what you are looking for. Still, heres a short tutorial for lists:# create a list l = [] # alternatively, use "l = list()" # add an element to a list l.append(1) # get the size of the list print(len(l)) # get the first element (index is 0 as indexes start with 0) print(l[0]) # prints "1" # remove the first element del l[0] # alternatively, use "l.pop(0)", which also returns the element
Now let's take a look at how lists could be used for your problem:
# number of players num_players = 4 # number of variables each player has num_vars = 10 # initiate a two-dimensional list with all players or variables # a two-dimensional list is a list of lists. In this case, all "variables" will be initialized as None. players = [[None] * num_vars] * num_players # set 2nd variable for player 3 to 12. Remember that indexes start at 0 players[2][1] = 12 # get 2nd variable for player 3 print(players[2][1]) # prints "12" # ============= alternative ============= # using math, we can do this a bit more efficient using 1-dimensional lists # number of players num_players = 4 # number of variables each player has num_vars = 10 # initiate a one-dimensional list with all players or variables players = [None] * num_vars * num_players # now we can access a variable by using index = (player_index * num_vars + var_index) # set 2nd variable for player 3 to 12. Remember that indexes start at 0 players[2 * num_vars + 1] = 12 # get 2nd variable for player 3 print(2 * num_vars + 1) # prints "12"
However, as I said before, lists aren't a good solution for this. Let's take a look at another datastructure, the
dict
. Adict
is a mapping of key-value pairs. Think of it like a dictionary, where each word you look up (in this case the key) has some associated words (the value). Here is an example of a dict usage:d = {} # alternatively, use "d = dict()" # set a key to a value d["name"] = "bennr01" # get the number of defined keys in a dict print(len(d)) # prints "1" # get a value for a key print(d["name]") # prints "bennr01" # remove a key-value pair del d["name"]
Using dicts, you can refer to the variables using names. Here's how to use it for your problem:
players = [] # create a player here player_1 = dict(name="Player 1", score=0) players.apend(player_1) # set the score for the first player (again, index 0) players[0]["score"] = 100 # get the score for the first player print(players[0]["score"]) # prints "100" # ============= alternative ============== # instead of using a list for all players, you could also use a dict players = {} # <-- see the difference # create a player here player_1 = dict(name="Player 1", score=0) players[1] = player_1 # set the score for the first player. As we are using a dict, we do not need to start with 0. We can even use strings players["pl_1"]["score"] = 100 # get the score for the first player print(players["pl_1"]["score"]) # prints "100"
Still, what you should be looking into are classes. Classes can have attributes and methods. As a tutorial would take too long, here is how you would use them:
class Player(object): """This class represents a player""" def __init__(self, name): self.name = name self.score = 0 def increment_score(self): """Increment the score by 1. This is an example for a method.""" self.score += 1 players = [] # create a player player = Player("bennr01") players.append(player) # get the name print(players[0].name) # prints "bennr01" # increase score players[0].increment_score() # print score print(players[0].score) # prints "1"
You can of course combine this with lists and dicts as needed.
-
bennr01
First of, you can move your
*_patient_list
into thePatient
class to reduce global variables.class Patient(object): master_patient_list = [] # this should be shared among all Patients def __init__(self, ...): ... self.master_patient_class.append(self)
Second, I think you want something like this for example:
class Physician(Employee): illness2doctor = {} # shared dict mapping illness -> doctor for illness def __init__(self, name): # just as example self.name = name @classmethod def register_doctor(cls, doctor, illness): assert not illness in cls.illness2doctor # prevent overwrite cls.illness2doctor[illness] = doctor @classmethod def get_doctor_for(cls, patient): illness = patient.illness if illness not in cls.illness2doctor: raise KeyError("No doctor for illness") return cls.illness2doctor[illness] # --- usage --- # create a new physician alice = Physician(name="Alice") # alice can treat "Broken Leg" Physician.register_doctor(alice, "Broken Leg") # now we can get the doctor for patient1 print(Physician.get_doctor_for(patient1).name) # -> should print "Alice"
-
bennr01
[s[i:i+2] for s in a for i in range(0, len(s), 2)]
Replace 2 with chunk length.
-
bennr01
You can also use six by running pip -6 install…, but I’ve found modules installed into Python 3 that way from Python 2 StaSh to be unreliable. You can import them, but sometimes they don’t work, and pip list doesn’t show them in either StaSh 2 or 3. So I just wouldn’t do it.
-6
does not usesix
, it just tells pip to use the shared site-packages directory so that you can install a package for both interpreters. Some packages may distribute different files depending on the installing python version which may cause the problems. Also, since pip stores information about the installed packages within site-packages, you must specify-6
forpip show
too (pip -6 show
). -
bennr01
StaSh runs on both py2 and py3, though not all commands support py3.
pip
uses the python interpreter StaSh was launched with and installs the package into the version specificsite-packages
directory. You can use the-6
option to tell pio that it should install a package into the sharedsite-packages
directory.You can force StaSh to use a specific python version by long-pressing the Run-Button and choosing the "run with python X" option.
-
bennr01
@JonB said:
data=read(f)
Shouldn't it be
f.read()
?I have to find all the numerical values in that text file and compute their sum. How can I do this in Pythonista?
Assuming each line has exactly one numerical value:
def read_ints_from_file(filepath): """ Read integers from file path filepath. """ values = [] # open file read-only with open(filepath, "r") as fin: # read file line by line for line in fin: # remove any leading/trailing whitespace characters and convert to integer v = int(line.strip()) values.append(v) return values # example usage. sum() calculates the sum of the argument(s) print(sum(read_ints_from_file("path/to/textfile.txt")))
If the file contains text other than the numbers, you should look into regular expressions (using
re
) to find the values. -
bennr01
/private/var/mobile/Containers/Shared/AppGroup/05D14C00-CCAC-4E98-A3CC-96C6944B8534/Pythonista3/Documents/site-packages/xmlrpc/__init__.py
Did you install this package using the
-6
parameter or did you use an outdated StaSh version for this installation? Normally, packages should now be installed only insite-package-3
orsite-packages-2
depending on the python version, but it seems likexmlrpc
is installed insite-packages
...@JonB said:
@bennr01 -- probably need to add xmlrpc to the blacklist...
It seems like in this case
xmlrpc
is provided by thefuture
package. -
bennr01
@mikael said:
@bennr01, a big thank you! for all you do to keep us stashed & pipped.
It's always a pleasure. Though in this case, the fix was made by yjqiang.
-
bennr01
After looking into this issue for a bit, it seems like the same bug as in Issue #364. This should have been fixed 12 months ago, just a month after the latest version bump for
master
. So it is possible that you have a version installed before that version bump.So, since it seems like the
master
branch became a bit outdated,I just merged 152 commits fromdev
intomaster
. This should include the fix as well as a version bump, so could you please try anotherselfupdate
? -
bennr01
would appreciate any hints on how to debug this?
In general,
stashconf py_traceback 1
,stashconf py_pdb 1
andpip --verbose install pythonista-gestures
.I just tried and could not replicate the error (it installs successfully).
Error matches a stash issue.
I think that one is a different issue. StaSh
pip
has two installers: one for source install (viasetup.py
) and one for wheels (.whl
). The linked issue was regarding the source install, while this issue is with wheel installations. Also, I think we already fixed the linked issue, but I am not sure...