0

I created multiply arrays and want to append something to them, but the user should choose which array he want append it to.

So to clarify what I mean: (The code down under is wrong, but I do not know how I could write it.)

x = []
y = []

def test(pName):
    %s.append(1) %pName

test(y)

Edit:

@Jim Fasarakis-Hilliard

I am trying to program in PyGame. Therefor I have to initalise all the images I want to use.

To not expand it, I wanted to create a function where you can easily append to any array you want to, so I do not have to create a new function every time I want to initalise new pictures.

My code looks like this atm.:

def loadImages(self,pName,pAnz,pScaleX,pScaleY):
    for i in range(0,pAnz):
        tux = pygame.transform.scale(pygame.image.load('./images/%s.png'),(pScaleX,pScaleY) % pName)
        self.%s.append(tux) %pName
    length_array = len(self.%s) %pName
    return length_array
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
freedome97
  • 167
  • 3
  • 15

3 Answers3

2

You could use globals, pass a string of the variable name to the function:

def test(pName):
    globals()[pName].append(1) 

test('y')

this, of course, relies on the name existing in the global scope.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
2

You could put the array's in a dictionary. Assuming that there is a fixed number of arrays, the code would look something like this:

arrays = {}
arrays['x'] = []
arrays['y'] = []

def test(pName):
    arrays[pName].append(1)

test('y')

You will want to check the user input, as a pName which is not a key in the dictionary will throw a key exception. If you want the arrays to be dynamic, you could do something like this:

arrays={}
def test(pName):
    if pName not in arrays.keys():
       arrays[pName]=[]
    arrays[pName].append(1)

test('y')
  • don't use try/except for this, if you know what the problem could be. `if pName not in array: ...` then create the key-value-pair. outside the `if` append the `1`. It's much cleaner. – Matthias Burger Dec 21 '16 at 16:47
  • @MatthiasBurger I don't see why a `try-except` block wouldn't be good in this example. It's commonly used for control flow and in this example it's expected that the user will input an already existing key, and if he/she doesn't it would be considered an exception from the normal case. And since we wouldn't need to get every string and compare it to `pName`, it would also be faster in the normal case (albeit slower in the exceptional case). I would also say that the `try-except` was as clean as the `if` since it showed what to do in the if there was a key and what to do if there wasn't. – Ted Klein Bergman Dec 21 '16 at 19:03
  • @TedKleinBergman I never said, try-except is not good here. It's just bad practice to use try-except when the possibly exception is known. there are some cases, when developers don't enter an exception-type and they gonna catch 'em all in pokémon-style (because try/except is so easy). maybe i had to write 'imho' or something and I'm one of possibly 30% who thinks if/else is better than try/except. SOTA is to use try-catch with cases you can't handle with an if. as you wrote: `what to do in the if there was a key and what to do if there wasn't` -> `if` – Matthias Burger Dec 22 '16 at 09:38
  • the mostly common definition is: You should use if / else to handle all cases you expect. You should use try-except in situations where you suspect something can/will go wrong and you don't want it to bring down the whole system, like network timeout/file system access problems, files doesn't exist, etc. - key is not in dictionary is something you expect – Matthias Burger Dec 22 '16 at 10:02
  • @MatthiasBurger I see your point and I would agree in other programming languages except for Python. It's more common in Python to implement [EAPF](https://docs.python.org/2/glossary.html#term-eafp) instead of [LBYL](https://docs.python.org/2/glossary.html#term-lbyl). In this case I interpreted (maybe wrongfully) that the user would try accessing the correct key, and in that case [try-except is preffered](http://stackoverflow.com/a/7604717/6486738). The exception in this example I see as a safety mechanism rather than an expected occurrence. – Ted Klein Bergman Dec 22 '16 at 13:34
  • The user would most likely access already created lists, hence the exception would be raised much more infrequent and thus would be [faster than an `if`](http://stackoverflow.com/a/1835844/6486738). So in Python I would suggest it's good practice, since it's faster, conventional and about as easy to read (in my opinion). – Ted Klein Bergman Dec 22 '16 at 13:34
1

If all you want is to be able to save your objects into different "namespaces", you can use dictionaries:

lists = {
   "x": [],
   "y": []
}

def test(pName):
    lists[pName].append(1)

test("y")

Cleaner and easier to understand than using globals or similars IMHO.

dfranca
  • 5,156
  • 2
  • 32
  • 60
  • Won't work. You should differentiate between `y` being name referencing an object and `'y'` begin one char string. – quapka Dec 21 '16 at 17:43