Python 按比例獲取樣本數(shù)據(jù)或執(zhí)行任務的實現(xiàn)代碼
按比例獲取樣本數(shù)據(jù)或執(zhí)行任務
By:授客 QQ:1033553122
開發(fā)環(huán)境
win 10
python 3.6.5
需求
已知每種分類的樣本占比數(shù),及樣本總數(shù),需要按比例獲取這些分類的樣本。比如,我有4種任務要執(zhí)行,分別為任務A,任務B,任務C,任務D, 要求執(zhí)行的總?cè)蝿沾螖?shù)為100000,且不同分類任務執(zhí)行次數(shù)占比為 A:B:C:D = 3:5:7:9,且在宏觀上這些任務同時進行
代碼實現(xiàn)
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'shouke' import time from copy import deepcopy def main(): class_propotion_map = {'A':3, 'B':5, 'C':7, 'D':7} # 分類及樣本數(shù)比例映射 class_list = [] # 分類 class_proption_list = [] # 存放分類樣本數(shù)比例 for class_type, propotion in class_propotion_map.items(): # 同一個循環(huán),可以保證比例索引和對應分類索引一一對應 class_list.append(class_type) class_proption_list.append(propotion) temp_class_propotion_list = deepcopy(class_proption_list) result = [] t1 = time.time() total_sample_num = 100000 #任務執(zhí)行次數(shù) for i in range(1, total_sample_num+1): max_propotion = max(temp_class_propotion_list) if max_propotion > 0: index = temp_class_propotion_list.index(max_propotion) result.append(class_list[index]) temp_class_propotion_list[index] -= 1 elif max_propotion == 0 and min(temp_class_propotion_list) == 0: temp_class_propotion_list = deepcopy(class_proption_list) index = temp_class_propotion_list.index(max(temp_class_propotion_list)) result.append(class_list[index]) temp_class_propotion_list[index] -= 1 t2 = time.time() from collections import Counter c = Counter(result) for item in c.items(): print(item[0], item[1]/total_sample_num) print('耗時:%s'%(t2-t1)) main()
運行結(jié)果
說明
以上方式大致實現(xiàn)思路就是,獲取每種分類樣本數(shù)所占比例副本數(shù)據(jù)列表,然后每次從中獲取最大比例值,并查找該比例值對應的分類(獲取分類后就可以根據(jù)需要構(gòu)造、獲取分類樣本數(shù)據(jù)),找到目標分類后,把比例數(shù)據(jù)副本中該比例值減1,直到最大比例和最小比例都等于0,接著重置比例副本數(shù)據(jù)為樣本數(shù)比例值,重復前面的過程,直到樣本數(shù)達到目標樣本總數(shù),這種方式實現(xiàn)的前提是得提前知道樣本總數(shù)及不同分類樣本數(shù)所占比例,且比例值為整數(shù)
到此這篇關(guān)于Python 按比例獲取樣本數(shù)據(jù)或執(zhí)行任務的文章就介紹到這了,更多相關(guān)Python獲取樣本數(shù)據(jù)執(zhí)行任務內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python中使用 Selenium 實現(xiàn)網(wǎng)頁截圖實例
這篇文章主要介紹了Python中使用 Selenium 實現(xiàn)網(wǎng)頁截圖實例,Selenium支持Java、C#、Ruby 以及 Python等語言,本文以Python語言為例,需要的朋友可以參考下2014-07-07matplotlib運行時配置(Runtime Configuration,rc)參數(shù)rcParams解析
這篇文章主要介紹了matplotlib運行時配置(Runtime Configuration,rc)參數(shù)rcParams解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-01-01python實現(xiàn)列表中由數(shù)值查到索引的方法
今天小編就為大家分享一篇python實現(xiàn)列表中由數(shù)值查到索引的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06Django實現(xiàn)whoosh搜索引擎使用jieba分詞
這篇文章主要介紹了Django實現(xiàn)whoosh搜索引擎使用jieba分詞,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-04-04python解釋器pycharm安裝及環(huán)境變量配置教程圖文詳解
這篇文章主要介紹了python解釋器pycharm安裝及環(huán)境變量配置教程圖文詳解,本文圖文并茂給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2020-02-02Python tornado隊列示例-一個并發(fā)web爬蟲代碼分享
這篇文章主要介紹了Python tornado隊列示例-一個并發(fā)web爬蟲代碼分享,具有一定借鑒價值,需要的朋友可以參考下2018-01-01