method of. it does not work the way I thought

0

I want to create a deck of cards that gets the first card after it shuffles

from random import shuffle

def doing_deck():
    value = ['a','2','3','4','5','6','7','8','9','t','j','q','k']
    suits = ['H','D','S','C',]
    cards = []

    for i in range(len(value)):
        for x in range(4):
            carlos =  [value[i] , suits[x]]
            carlos = "".join(carlos)
            cards.append(carlos)
    return cards

cards1 = doing_deck() #cards1 agarra cards sin combinar

def get_shuffled_deck():
    shuffle(cards1)
    return cards1

list1 = get_shuffled_deck()     
print list1

def deal_card(list1):
    print list1[0]
    del list1[0]

deal_card(list1)
print list1

get_shuffled_deck()

Deal_card() takes an argument (a list) and should do two things: remove the first element and return it. The problem is that it simply eliminates it. How could I do what I want?

    
asked by PapitaRellena 12.04.2017 в 20:55
source

1 answer

1

In order to eliminate and return the element you must use the pop(index) method, del only deletes it but does not return anything.

def deal_card(list1):
    return list1.pop(0)

carta = deal_card(list1)
print(carta)
print(list1)

Another recommendation is that to combine the cards do not use indexes, iterate directly on the elemntos. It is more 'pythonic' and more efficient:

def doing_deck():
    value = ['a','2','3','4','5','6','7','8','9','t','j','q','k']
    suits = ['H','D','S','C',]
    cards = []

    for v in value:
        for x in suits:
            carlos = "".join((v,x))
            cards.append(carlos)
    return cards

Or use list compression directly:

def doing_deck():
    value = ['a','2','3','4','5','6','7','8','9','t','j','q','k']
    suits = ['H','D','S','C',]
    return ["".join((v,x)) for x in suits for v in values]

Another efficient option is to use itertools.product() .

The code could look like this:

from random import shuffle
from itertools import product

def doing_deck():
    value = ['a','2','3','4','5','6','7','8','9','t','j','q','k']
    suits = ['H','D','S','C',]
    return ["".join((v,x)) for v, x in product(value, suits)]

def get_shuffled_deck(cards):
    shuffle(cards)

def deal_card(cards):
    return cards.pop(0)


if __name__ == '__main__':
    print 'Obteniendo mazo de cartas'
    cards = doing_deck()
    print 'Barajando...'
    get_shuffled_deck(cards)
    carta1 = deal_card(cards)
    print 'Primera carta obtenida: {}.'.format(carta1)
    get_shuffled_deck(cards)
    print('Barajando...')
    carta2 = deal_card(cards)
    print 'Segunda carta obtenida: {}.'.format(carta2)
    
answered by 12.04.2017 / 21:45
source