Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
57 views
in Technique[技术] by (71.8m points)

python - trying to yield return with remove

I need to generate an iterator for a deck of cards. I MUST NOT use another import but random.

I don't understand why if I removes cards from the deck after yield I get after a few tries "ValueError: list.remove(x): x not in list"

Is it because I am changing the deck inside the for? how can I solve it without import deep copy? tnx

import random

NUMS_IN_DECK = 13

def take_card():
    type_cards = "diamond", "heart", "spade", "club"
    deck = [(i + 1 ,t)  for i in range(NUMS_IN_DECK) for t in type_cards]
    
    for i in range(NUMS_IN_DECK * len(type_cards)):
        card_to_return = random.sample(deck, 1)
        yield card_to_return
        deck.remove(card_to_return)

card_iter = take_card()

for i in range(10):
    print(next(card_iter))
question from:https://stackoverflow.com/questions/65833694/trying-to-yield-return-with-remove

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As pointed out in the comments, the problem is that random.sample returns a list, and that list is never in deck, but you are over-complicating this. Just do:

import random

NUMS_IN_DECK = 13

def take_card():
    type_cards = "diamond", "heart", "spade", "club"
    deck = [(i + 1 ,t)  for i in range(NUMS_IN_DECK) for t in type_cards]
    random.shuffle(deck)
    for card in deck:
        yield card

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...