Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I make a loop output to two different lists?

I have run into a block in my python code where i’m not sure how to make a loop split an output into two different lists. Here is my code:

def GameStart(AmountPlayers):
    players = []

    for player in range(AmountPlayers):
        hand = TakeCards(5)

        players.append(hand)

        print(hand)
        returncard(hand)

This function outputs this if 2 is entered for AmountPLayers:

['blue_skip', 'blue_9', 'green_5', 'green_9', 'red_1']
['yellow_skip', 'green_6', 'yellow_8', 'red_9', 'blue_3']

However both of these are outputs of the variable hand.
I need to acess these lists separately, so need to find a way of putting each list into separate variables, e.g hand1 or hand2, and so on until hand 4 (the maximum number of players).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Does anyone know a way of doing this?

Cheers

>Solution :

Assuming the objective is to obtain two lists with cards drawn for that player, this is the code:

from random import choice, randint

deck = list(range(1, 11))
def TakeCard():
    global deck
    a = choice(deck)
    deck.remove(a)
    return a
        
def GameStart(AmountPlayers):
    global deck
    numOfCards = 5
    players = [[]for _ in range(AmountPlayers)]
    for _ in range(numOfCards):
        for player in range(0, AmountPlayers):
            players[player].append(TakeCard())
    return players
        
print(GameStart(2))

This returns a list of two lists as:

[[4, 5, 7, 6, 3], [10, 2, 9, 1, 8]]

Replace the elements of deck with card names.

Optional alternate solution. If you plan on displaying images, use previous one since it allots cards one by one and maybe you can add animations. This one allots all cards to one player at once:

from random import choice

deck = list(range(1, 11))
def TakeCards(n):
    global deck
    z = []
    for _ in range(n):
        a = choice(deck)
        deck.remove(a)
        z.append(a)
    return z
        
def GameStart(AmountPlayers):
    global deck
    return [TakeCards(5) for _ in range(AmountPlayers)]
        
print(GameStart(2))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading