Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 205
ritratt Avatar asked Jul 06 '26 00:07

ritratt


2 Answers

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.

like image 91
Mark Byers Avatar answered Jul 07 '26 15:07

Mark Byers


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.

like image 22
Ramin Omrani Avatar answered Jul 07 '26 15:07

Ramin Omrani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!