【问题标题】:What's wrong with this code Python 3.3这段代码 Python 3.3 有什么问题
【发布时间】:2013-11-30 10:25:31
【问题描述】:

我正在尝试创建一个小型 Python 程序,该程序在课程中调用随机学生,然后从列表中删除该学生,直到调用所有其他学生。

例子:

  1. 其他

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

  1. 其他

我已经编写了这段代码,但它不断重复学生,而没有先调用所有学生。

    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

【问题讨论】:

  • 为什么添加只是为了删除?
  • @IgnacioVazquez-Abrams 所以当所有列表都被调用时删除并重新开始。
  • 这段代码没有显示错误。
  • @user2357112 它在语法上没有错误,但它有一个逻辑错误,因为我希望它从 dict 中调用所有元素然后重复,但它在调用所有其他希望之前没有重复同一个学生清楚!!!
  • 不要在for 循环中添加或删除任何项目。

标签: python random random-seed


【解决方案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),因为 .keys 不会像 2.x 那样返回列表

【讨论】:

  • Ty 提供答案和解释,但在 python 3.3 上运行显示和字典索引错误...
  • @KillerB 见注释
  • keys 在 3.x 中返回一个字典视图;只需改用list(klasa)
【解决方案2】:

我尽量简单:

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

【讨论】:

    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-25
      • 2018-09-09
      相关资源
      最近更新 更多