未加星标

What's new with this Python 3.3 code

字体大小 | |
[开发(python) 所属分类 开发(python) | 发布者 店小二04 | 时间 2019 | 作者 红领巾 ] 0人收藏点击收藏

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开发工程师 软件开发工程师 软件开发流程

代码区博客精选文章
分页:12
转载请注明
本文标题:What's new with this Python 3.3 code
本站链接:https://www.codesec.net/view/627796.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 开发(python) | 评论(0) | 阅读(99)