这段代码python3.3有什么问题

2024-10-01 09:39:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着创建一个小的Python程序,它在课程中随机调用一个学生,然后从列表中删除这个学生,直到调用所有其他学生。你知道吗

示例:

  1. ME
  2. You
  3. Others

我想随机调用一个,然后将其从列表中删除,这样下次它将只

  1. You
  2. 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

Tags: 代码inimport程序you示例列表random
3条回答

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

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

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

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)

注意:在python3.x中,您需要转到keys = list(klasa),因为.keys不像2.x那样返回列表

为了简单起见:

>>> 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
>>> 

相关问题 更多 >