我试着创建一个小的Python程序,它在课程中随机调用一个学生,然后从列表中删除这个学生,直到调用所有其他学生。你知道吗
示例:
- ME
- You
- Others
我想随机调用一个,然后将其从列表中删除,这样下次它将只
- You
- Others
我写了这个代码,但它不断地重复学生没有首先调用所有的学生。你知道吗
import random
klasa = {1 :'JOHN', 2 : 'Obama' , 3 : 'Michele' , 4 : 'Clinton'}
ran = []
random.seed()
l = random.randint(1,4)
while l not in ran:
ran.append(l)
print(klasa[l])
for x in ran:
if x != None:
ran.remove(x)
else:
break
根据您的需要修改此解决方案
你可以采取两种方法。一种是在字典中有一个键列表,从这个列表中随机选择一个键,然后将其删除。这看起来像这样:
klasa.pop(key)
除了删除键之外,还将返回与该键关联的值:另一种方法是在交钥匙之前将钥匙列表洗牌,然后逐一检查,即:
如果要一次删除一个人,只需执行以下操作:
虽然这意味着您每次都将生成一个键列表,但最好将其存储在一个列表中,并在删除键时将其从列表中删除,就像第一个建议的方法一样。
keys = .keys() ... a_key = choice(keys), klasa.pop(key), keys.delete(key)
注意:在python3.x中,您需要转到
keys = list(klasa)
,因为.keys
不像2.x那样返回列表为了简单起见:
相关问题 更多 >
编程相关推荐