1

I'm trying to create a small Python program which calls a random student in lessons then it removes this student from the list till all other students are called.

Example :

  1. ME
  2. You
  3. Others

I want to call randomly one and then remove it from the list so the next time it would be only

  1. You
  2. Others

I've wrote this code but it keeps repeating students without first calling all of them.

    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
4

3 回答 3

1

您可以采取两种方法。一种是在字典中有一个键列表,从该列表中随机选择一个键,然后将其删除。这看起来像这样:

from random import choice

keys = klasa.keys()
while keys: #while there are keys left in 'keys'
    key = choice(keys) #get a random key
    print("Calling %s" % (klasa.pop(key))) #get the value at that key, and remove it
    keys.remove(key) #remove key from the list we select keys from

klasa.pop(key)除了删除它之外,还将返回与键关联的值:

 |  pop(...)
 |      D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
 |      If key is not found, d is returned if given, otherwise KeyError is raised

另一种方法是事先打乱键列表并检查每个键,即:

from random import shuffle

keys = klasa.keys()
shuffle(keys) #put the keys in random order
for key in keys:
    print("Calling %s" % (klasa.pop(key)))

如果您想一次删除一个人,您可以简单地执行以下操作:

print("Calling %s" % klasa.pop(choice(klasa.keys())))

虽然这意味着您每次都会生成一个键列表,但最好将其存储在一个列表中,并在删除时从该列表中删除键,就像在第一个建议的方法中一样。 keys = .keys() ... a_key = choice(keys), klasa.pop(key), keys.delete(key)

注意:在 python 3.x 中,你需要去keys = list(klasa)as.keys不会返回像 2.x 这样的列表

于 2013-11-30T10:38:08.873 回答
0

为了简单起见,我尝试了:

>>> klasa = ['JOHN', 'Obama' , 'Michele' , 'Clinton']
>>> random.seed()
>>> l = len(klasa)
>>> while l > 0:
...     i = random.randint(0,l-1)
...     print (klasa[i])
...     del klasa[i]
...     l=len(klasa)
... 
Michele
JOHN
Obama
Clinton
>>> 
于 2013-11-30T10:43:47.417 回答
0

根据您的需要修改此解决方案

from random import *

klasa = {1 :'JOHN', 2 : 'Obama' , 3 : 'Michele' , 4 : 'Clinton'}

#Picks a random Student from the Dictionary of Students 
already_called_Student=klasa[randint(1,4)]
print "Selected Student is" ,  already_called_Student
total_Students = len(klasa)
call_student_number = 0

while  call_student_number < total_Students:
    random_student=klasa[randint(1,4)]
    if random_student == already_called_Student:
        continue
    print random_student 
    call_student_number =   call_student_number  + 1
于 2013-11-30T12:12:02.123 回答