从列表中弹出一个整数并继续运行直到列表消失?

时间:2017-03-26 21:15:13

标签: python list function

我创建了一个随机列表并尝试使用.remove()弹出一个数字然后继续,但它一直给我错误,pop index超出范围。即使import random hand= [] for i in range(10): hand.append(random.randrange(1,10)) print (hand) userInput = int(input("What card do you want to play? ")) while True: if userInput > 0: hand.pop(userInput) 无效。

<select id="cmd-id" class="selectpicker form-control" data-dropup-auto="false" data-size="6" name="cmd-id" onchange="command = this.value; command_string();">
    <option value="cmd1">1</option>
    <option value="cmd2">2</option>
</select>

2 个答案:

答案 0 :(得分:1)

你的while循环的条件必须是确定手册的长度是否大于零。如果它为零,因此为空,它必须停止。

import random

hand= []


for i in range(10):
    hand.append(random.randrange(1,10))
print (hand)



while len(hand) > 0:
     userInput = int(input("What card do you want to play? "))
     card = hand.pop(userInput)
     print card

请注意,pop()会删除索引处的值并将其返回,因此您可能希望存储返回的值并将其打印出来,或者对其执行其他操作。

答案 1 :(得分:0)

我使用了@ Ajax1234的代码,我改变的唯一事情是不使用列表中的卡片索引来删除,而是使用了它的值。例如,如果我们有以下列表:

hand = [2, 5, 6, 1, 3, 8, 9]

如果我想玩卡号3,而不是指定索引(4),我会声明它的值(3)。

以下是我使用的代码:

import random

hand= []

for i in range(10):
    hand.append(random.randrange(1,10))
print(hand)

while len(hand) > 0:
     userInput = int(input("What card do you want to play? "))
     hand.remove(userInput)
     print(hand)