Reputation:
I am creating a simple card game and decided to implement list comprehension well try to. I don't really know how to approach this because I have only dealt with 1 for loop.
def __init__(self):
self.cards = []
for suit in range(1, 5):
for value in range(2, 11):
self.cards.append(Card(value, suit))
for value in ['Ace', 'King', 'Queen', 'Jack']:
self.cards.append(Card(value, suit))
This is the nested for loop that I want to possibly put into a list comprehension, if possible. Any ideas?
Upvotes: 0
Views: 90
Reputation: 96350
Sure. The neatest way would leverage itertools.chain
, so first:
from itertools import chain
Then simply:
def __init__(self):
self.cards = [
Card(value, suit)
for suit in range(1, 5)
for value in chain(range(2, 11), ['Ace', 'King', 'Queen', 'Jack'])
]
Or even without itertools
:
num_vals = range(2, 11)
face_vals = ['Ace', 'King', 'Queen', 'Jack']
self.cards = [
Card(value, suit))
for suit in range(1, 5)
for values in (num_vals, face_vals)
for value in values
]
Upvotes: 1
Reputation: 59239
With nested loops you can write the comprehension as:
[expression for x in x_values for y in y_values]
Something like this:
def __init__(self):
values = list(range(2,11)) + ['Ace', 'King', 'Queen', 'Jack']
self.cards = [Card(value, suit) for suit in range(1,5) for value in values]
I set up the values
in a separate line so the comprehension wasn't too unwieldy. You could put it elsewhere as a constant if you were so inclined.
Upvotes: 1