简体   繁体   English

如何显示然后从列表中删除随机字符串?

[英]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 . 所以执行random.shuffle(bingo)然后遍历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 1)使用随机索引并弹出

import random

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

2) use random choice them remove 2)使用随机选择将其删除

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 如果您希望所有元素都以随机顺序排列,那么最好是将列表改组然后对其进行迭代,或者反复调用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 :]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM