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

ふたつのやり方:

リストの「Index」メソッドを使用して、アイテムのインデックスを取得します。

card.index(guess)

または、要素ではなくインデックスをランダムに選択します。

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

ただし、他の回答が指摘したように、このタスクを達成するために実際のインデックスを取得する必要はありません

于 2014-09-04T21:45:26.717 に答える