omz:forum

    • Register
    • Login
    • Search
    • Recent
    • Popular

    Welcome!

    This is the community forum for my apps Pythonista and Editorial.

    For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.


    Problem with arrays

    Pythonista
    3
    4
    1531
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • Python567
      Python567 last edited by ccc

      I want to have four players in an array. Every array has the same variables how can I do that? It‘s my first time to use arrays so I don‘t know how to use them.

      1 Reply Last reply Reply Quote 0
      • bennr01
        bennr01 last edited by ccc

        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 a list 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. A dict 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.

        madivad 1 Reply Last reply Reply Quote 3
        • Python567
          Python567 last edited by ccc

          @bennr01 thanks for your great answer, I think that is that what I need for my program.

          1 Reply Last reply Reply Quote 0
          • madivad
            madivad @bennr01 last edited by

            @bennr01 That is a brilliant and well constructed reply. Great work.

            1 Reply Last reply Reply Quote 0
            • First post
              Last post
            Powered by NodeBB Forums | Contributors