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],但我知道它需要一个整数。如何将猜测转换为整数然后从列表中删除del以便它不会猜测?
答案 0 :(得分: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))
答案 1 :(得分:0)
两种方式:
使用"索引"获取项目索引的列表方法:
card.index(guess)
或者让你的随机选择选择索引而不是元素:
guess = random.choice(range(len(card)))
正如其他一些答案指出的那样,你不需要获得实际索引来完成这项任务