代码区项目交易流程

What's new with this Python 3.3 code


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 :

ME You Others

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

You 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

There are two approaches you could take. One is to have a list of keys in the dictionary, select a key randomly from this list and then remove it. This would look like this:

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) will return the value associated with the key in addition to deleting it:

| 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

Another approach is to shuffle the list of keys before hand and go over each one, i.e:

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

If you want to delete people one person at time, you can simply do:

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

Though this means you will generate a list of the keys each time, it's better to store this in a list and remove the keys from this list as you delete them like in the first suggested method. keys = .keys() ... a_key = choice(keys), klasa.pop(key), keys.delete(key)

Note: In python 3.x you need to go keys = list(klasa) as .keys doesn't return a list like 2.x

本文开发(python)相关术语:python基础教程 python多线程 web开发工程师 软件开发工程师 软件开发流程

点击收藏

LAST Learning Jinja2: Part 4: Template Inheritance and Blocks Python 中的 urlencode 和 urldecode 操作 NEXT