Louis Cowen
Louis Cowen

Reputation: 1

Python - generating objects with variable names based on list items

I am a beginner to python and for all i know, i could be doing this completely wrong. I am trying to make a blackjack game and was just wondering if there was any way to generate items that are part of a class using a list of values and a for loop based on the items in the list. So far, I have made it print each of the card values but am struggling to assign them to an object in the Card class.

suits = ['Spades', 'Clubs', 'Hearts', 'Diamonds']
values = [2,3,4,5,6,7,8,9,10,'Ace','Jack','Queen','King']

class Card(object):

    def __init__(self, suit, value):
        self.suit = suit
        self.value = value

As i mentioned earlier, i have made the for loop that i'm using print the values that i want to be assigned to objects:

for cardSuit in suits:
    for cardValue in values:
        print cardSuit, cardValue

As shown bellow, i am trying to create an instance of an object with the Card class using the name of the suit and value of a card and then assign the values of cardSuit and cardValue to the object.

for cardSuit in suits:
    for cardValue in values:
        cardSuit,cardValue = Card(suit = cardSuit,value = cardValue)

Any advice or improvements i can do here would be much appreciated since i am trying to teach myself how to use python and am stuck with this one.

Upvotes: 0

Views: 67

Answers (1)

binbin
binbin

Reputation: 177

You can try this:

cards = [Card(cardSuit, cardValue) for cardSuit in suits for cardValue in values]

Also,You need not to use a class, namedtuple may be better

from collections import namedtuple
Card = namedtuple('Card', ['suit', 'value'])
cards = [Card(cardSuit, cardValue) for cardSuit in suits for cardValue in values]

Upvotes: 1

Related Questions