简体   繁体   中英

List comprehension for nested for loops

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?

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.

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
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM