0
import random  
card = ['ace of spades', 'two of spades', 'three of spades', 'four of spades',  
    'five of spades', 'six of spades', 'seven of spades',  
    'eight of spades', 'nine of spades', 'ten of spades',  
    'jack of spades', 'queen of spades', 'king of spades',  
    'ace of clubs', 'two of clubs', 'three of clubs', 'four of clubs',  
    'five of clubs', 'six of clubs', 'seven of clubs',  
    'eight of clubs', 'nine of clubs', 'ten of clubs',  
    'jack of clubs', 'queen of clubs', 'king of clubs',  
    'ace of hearts', 'two of hearts', 'three of hearts', 'four of hearts',  
    'five of hearts', 'six of hearts', 'seven of hearts',  
    'eight of hearts', 'nine of hearts', 'ten of hearts',  
    'jack of hearts', 'queen of hearts', 'king of hearts',  
    'ace of diamonds', 'two of diamonds', 'three of diamonds', 'four of diamonds',  
    'five of diamonds', 'six of diamonds', 'seven of diamonds',  
    'eight of diamonds', 'nine of diamonds', 'ten of diamonds',  
    'jack of diamonds', 'queen of diamonds', 'king of diamonds']  
answer = input('Pick a card:\n')  
guess = random.choice(card)  
guesses = 1  
while guess != answer:  
    if guess != card:  
        guess = random.choice(card)  
        print(guess)  
    guesses += 1  
print('\nWhoopy, I guessed right!\n')  
print('It only took me %s guesses to guess %s.' % (guesses, answer))  

所以这是我的代码。我试图添加到 if 语句... del card[:guess],但我知道它需要一个整数。我怎样才能把猜测变成一个整数,然后从列表中删除,这样它就不会欺骗猜测?

4

2 回答 2

1

只需从列表中删除该项目card.remove(guess)

answer = input('Pick a card:\n')
guess = random.choice(card)
guesses = 1
while guess != answer:
    if guess != card:            
        guess = random.choice(card)
        card.remove(guess)
    guesses += 1
print('\nWhoopy, I guessed right!\n')
print('It only took me %s guesses to guess %s.' % (guesses, answer))
于 2014-09-04T21:44:23.697 回答
0

两种方式:

使用列表的“索引”方法获取项目的索引:

card.index(guess)

或者让您的随机选择选择一个索引而不是一个元素:

guess = random.choice(range(len(card)))

正如其他一些答案指出的那样,您无需获取实际索引即可完成此任务

于 2014-09-04T21:45:26.717 回答