简体   繁体   中英

How can I display and then delete a random string from a list?

I want to make a game of science bingo for my class. This code currently randomly picks an element from the list and displays it, but I don't know how to delete that value from the list so it is not randomly reprinted.

from random import randint
bingo=["H", "He", "C", "O"]
total=((len(bingo))-1)
while (total>0):
    finish=input("Bingo?")
    if (finish=="no"):
        a=randint(0,int(total))
        b=(bingo[int(a)])
        print (b)

No need to delete from your list. Just shuffle it and iterate over it once. It will be faster and you can reuse your original list. So do random.shuffle(bingo) then iterate over bingo .

Here is how to incorporate this into your original code:

import random
bingo=["H", "He", "C", "O"]
random.shuffle(bingo)
for item in bingo:
    if input("Bingo?") == "no":
        print item
    else:
        break

阅读后,使用del

del bingo[int(a)]

If you want to do this once you have a couple of options

1) Use a random index and pop

import random

i = random.randrange(0, len(bingo))
elem = bingo.pop(i)  # removes and returns element

2) use random choice them remove

import random

elem = random.choice(bingo)
bingo.remove(elem)

If you want all of the elements in a random order, then you're better off just shuffling the list and then either iterating over it, or repeatedly calling pop

import random

random.shuffle(bingo)
for elem in bingo: # list is not shuffled
    ...

or

import random

random.shuffle(bingo)
while bingo:
    elem = bingo.pop()
    ...
foo = ['a', 'b', 'c', 'd', 'e']
from random import randrange
random_index = randrange(0,len(foo))

For displaying:

print foo[random_index]

For deletion:

foo = foo[:random_index] + foo[random_index+1 :]

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