国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python實現年會抽獎程序

2020-02-16 00:49:33
字體:
來源:轉載
供稿:網友

用python來實現一個抽獎程序,供大家參考,具體內容如下

主要功能有

1.從一個csv文件中讀入所有員工工號
2.將這些工號初始到一個列表中
3.用random模塊下的choice函數來隨機選擇列表中的一個工號
4.抽到的獎項的工號要從列表中進行刪除,以免再次抽到

初級版

這個比較簡單,缺少定制性,如沒法設置一等獎有幾名,二等獎有幾名

import csv#創建一個員工列表emplist = []#用with自動關閉文件with open('c://emps.csv') as f: empf = csv.reader(f) for emp in empf:  emplist.append(emp)print("進行一等獎抽獎,共有一名")import random#利用random模塊的chice函數來從列表中隨機選取一個元素e1 = random.choice(emplist)#將中獎的員工從列表中剔除emplist.remove(e1)print('一等獎得主的號碼是 %s' % e1)print('進行三個二等獎的號碼抽獎')e2_1 = random.choice(emplist)emplist.remove(e2_1)e2_2 = random.choice(emplist)emplist.remove(e2_2)e2_3 = random.choice(emplist)emplist.remove(e2_3)print('獲得3個二等獎是 %s %s %s',(e2_1,e2_2,e2_3))#下面依次類推可以設置三等獎的抽獎

改進版

上面的那個初級版,假如要設置個三等獎一百名那么將要重新維護幾百行代碼,下面用比較高級點的辦法實現.

我們考慮用面向對象來實現,設計一個抽獎類,類中包含一個屬性(號碼來源),一個方法:產生所有抽獎層次指定個數的抽獎號碼。

用到如下知識點:

1. csv模塊部分函數用法
2. sys模塊讀取輸入
3. random模塊函數choice函數用法
4. 列表和字典元素的添加、刪除
6. for循環中range用法
7. 類和面向對象
8. 字符打印,print中的計算
9.open中with

#!/usr/bin/python#coding=utf-8import csvimport sysimport randomreload(sys) sys.setdefaultencoding('utf8')#coding=utf-8print("開始進行抽獎")#定義個抽獎類,功能有輸入抽獎級別和個數,打印出每個級別的抽獎員工號碼class Choujiang: #定義scv文件路徑 def __init__(self,filepath):  self.empfile = filepath def creat_num(self):  emplist = []  with open(self.empfile) as f:   empf = csv.reader(f)   for emp in empf:    emplist.append(emp)  print('共有%s 人參與抽獎' % len(emplist))  levels = int(input('抽獎分幾個層次,請輸入:'))  #定義一個字典  level_dict = {}  for i in range(0,levels):   print('請輸入當前獲獎層次 %s 對應的獎品個數' % ( i + 1))   str_level_dict_key = sys.stdin.readline()   int_level_dict_key = int(str_level_dict_key)   level_dict[i] = int_level_dict_key   #循環完成后抽獎層次字典構造完畢  #進行抽獎開始  print('抽獎字典設置為: %s' % level_dict)  for i in range(0,len(level_dict)):   winers = []   #產生當前抽獎層次i對應的抽獎個數   for j in range(0,int(level_dict[i])):    #利用random模塊中的choice函數從列表中隨機產生一個    winer = random.choice(emplist)    winers.append(winer)    emplist.remove(winer)   print('抽獎層次 %s 下產出的獲獎人員有:' % (i + 1 ))   print(winers)#類功能定義完畢,開始初始化并使用if __name__ == '__main__': peoples = Choujiang('c://emps.csv') peoples.creat_num()            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 安乡县| 澄城县| 永年县| 开封县| 福清市| 晋城| 汽车| 醴陵市| 开阳县| 唐河县| 利川市| 西和县| 津市市| 师宗县| 南宫市| 三台县| 筠连县| 横山县| 涿鹿县| 卓资县| 崇明县| 长武县| 武强县| 固原市| 溧阳市| 阿荣旗| 若羌县| 抚顺县| 海宁市| 赤壁市| 沙雅县| 兰坪| 桐城市| 融水| 抚州市| 五台县| 上林县| 若尔盖县| 石景山区| 三门县| 黄龙县|