简体   繁体   中英

How do I check if multiple elements of a list are equal to a variable?

I am trying to make a shuffled playing card deck and in order to do so I have to check if the generated card is equal to the previous ones. So far I have tried this:

for i in range(51):
a=card()
while(deck[:i]==a):
    a=card()
deck[i]=a

card is the function that generates a random card I think that the problem is in the [:i] PS The list already has 52 elements and they are all set as "Empty"

To answer your question, you can do something like this:

for i in range(51):
    a = card()
    while a in deck:
        a = card()
    deck[i] = a

You can test for membership using a in deck because you said that deck is initialized to empty, so you don't have to check up to the i'th element, as the elements after i definitely won't contain a.

However, there is a better way to create a shuffled deck of cards: use random.shuffle as ctj232 said.

>>> import random
>>> l = [1, 2, 3, 4, 5]
>>> random.shuffle(l)
>>> l
[3, 5, 4, 2, 1]

Make a list that represents all 52 cards in order, making your own class or just integers, then use the random library to shuffle them.

You can also do something like:

    import random

    cards = [  i for i in range(52)]
    curentPosition = [  i for i in range(52)]
    nextPosition = [  i for i in range(52)]

    print('Positions before shufle:\n',curentPosition)

    for i in cards:
        randomPos = random.choice(nextPosition)
        curentPosition[i] = randomPos
        nextPosition.remove(randomPos)


    print('Positions after shufle\n',curentPosition)

Using random.shuffle is absolutely the best way to solve your issue as the other answer has explained, but to answer your original question:

To check if multiple elements of a list are equal to a variable, you can use the variable in list syntax:

my_list = [51,47,2,29,6]
if 51 in my_list:
    print("51 is already selected")
else:
    print("51 isn't in my_list")

To apply this to your existing code:

for i in range(51):
    a=card()
    while(a in deck):
        a=card()
    deck[i]=a

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