ritratt
ritratt

Reputation: 1858

List comprehension without using an iterable

I am trying to build a list by picking random elements from another list with no duplicates. Think shuffling a pack of cards. I could obviously write some unpythonic code for this, which I dont want to.

So here is what I am trying to do:

new = [deck[i] where 0<(i = some_rand_int)<51 if new.count(deck[i]) == 0]

Is there a way to do this?

Upvotes: 3

Views: 220

Answers (2)

Ramin Omrani
Ramin Omrani

Reputation: 3761

You can use generators for this:

import random

def pick(deck):
    while True:
        try:
            newCard = random.choice(deck)
            deck.remove(newCard)
        except:
            print 'deck is empty...'
        yield newCard

def resetDeck():
    deck = []
    newCard = None
    for i in range(1,53):
        deck.append(i)
    return deck

pick(deck) picks a card from deck and if you wanted to recreate the deck use resetDeck(). after implementing, use pick(deck).next() to choose card from deck.

Upvotes: 2

Mark Byers
Mark Byers

Reputation: 839114

I am trying to build a list by picking random elements from another list with no duplicates.

Use random.sample:

random.sample(population, k)

Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.

Try this:

result = random.sample(deck, n)

To shuffle the entire list use random.shuffle:

random.shuffle(deck)

Still curious if this can be done using list comprehension though!

Not really. A list comphrension preserves the order of the elements, but allows you to project them or filter them. Shuffling is not a projection or a filter.

Upvotes: 14

Related Questions