简体   繁体   中英

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?

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 ak 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.

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.

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