问题:
例如我们要选从不同省份选取一个号码,每个省份的权重不一样,直接选随机数肯定是不行的了,就需要一个模型来解决这个问题。
简化成下面的问题:
字典的key代表是省份,value代表的是权重,我们现在需要一个函数,每次基于权重选择一个省份出来
{"A":2, "B":2, "C":4, "D":10, "E": 20}
解决:
这是能想到和能看到的最多的版本,不知道还没有更高效好用的算法。
#!/usr/bin/env python # -*- coding: utf-8 -*- #python2.7x #random_weight.py #author: orangleliu@gmail.com 2014-10-11 ''''' 每个元素都有权重,然后根据权重随机取值 输入 {"A":2, "B":2, "C":4, "D":10, "E": 20} 输出一个值 ''' import random import collections as coll data = {"A":2, "B":2, "C":4, "D":6, "E": 11} #第一种 根据元素权重值 "A"*2 ..等,把每个元素取权重个元素放到一个数组中,然后最数组下标取随机数得到权重 def list_method(): all_data = [] for v, w in data.items(): temp = [] for i in range(w): temp.append(v) all_data.extend(temp) n = random.randint(0,len(all_data)-1) return all_data[n] #第二种 也是要计算出权重总和,取出一个随机数,遍历所有元素,把权重相加sum,当sum大于等于随机数字的时候停止,取出当前的元组 def iter_method(): total = sum(data.values()) rad = random.randint(1,total) cur_total = 0 res = "" for k, v in data.items(): cur_total += v if rad<= cur_total: res = k break return res def test(method): dict_num = coll.defaultdict(int) for i in range(100): dict_num[eval(method)] += 1 for i,j in dict_num.items(): print i, j if __name__ == "__main__": test("list_method()") print "-"*50 test("iter_method()")
一次执行的结果
A 4 C 14 B 7 E 44 D 31 -------------------------------------------------- A 8 C 16 B 6 E 43 D 27
思路:
思路都很原始可以参考下面的连接,还有别的好方法一起交流!!
代码: https://gist.github.com/orangle/d83bec8984d0b4293710
参考:
http://www.bitsCN.com/article/65060.htm
http://www.bitsCN.com/article/65058.htm

numpyArraysareAreBetterFornumericalialoperations andmulti-demensionaldata,而learthearrayModuleSutableforbasic,內存效率段

numpyArraySareAreBetterForHeAvyNumericalComputing,而lelethearRayModulesiutable-usemoblemory-connerage-inderabledsswithSimpleDatateTypes.1)NumpyArsofferVerverVerverVerverVersAtility andPerformanceForlargedForlargedAtatasetSetsAtsAndAtasEndCompleXoper.2)

ctypesallowscreatingingangandmanipulatingc-stylarraysinpython.1)usectypestoInterfacewithClibrariesForperfermance.2)createc-stylec-stylec-stylarraysfornumericalcomputations.3)passarraystocfunctions foreforfunctionsforeffortions.however.however,However,HoweverofiousofmemoryManageManiverage,Pressiveo,Pressivero

Inpython,一個“列表” isaversatile,mutableSequencethatCanholdMixedDatateTypes,而“陣列” isamorememory-sepersequeSequeSequeSequeSequeRingequiringElements.1)列表

pythonlistsandArraysareBothable.1)列表Sareflexibleandsupportereceneousdatabutarelessmory-Memory-Empefficity.2)ArraysareMoremoremoremoreMemoremorememorememorememoremorememogeneSdatabutlesserversEversementime,defteringcorcttypecrecttypececeDepeceDyusagetoagetoavoavoiDerrors。

Python和C 各有優勢,選擇應基於項目需求。 1)Python適合快速開發和數據處理,因其簡潔語法和動態類型。 2)C 適用於高性能和系統編程,因其靜態類型和手動內存管理。

選擇Python還是C 取決於項目需求:1)如果需要快速開發、數據處理和原型設計,選擇Python;2)如果需要高性能、低延遲和接近硬件的控制,選擇C 。

通過每天投入2小時的Python學習,可以有效提升編程技能。 1.學習新知識:閱讀文檔或觀看教程。 2.實踐:編寫代碼和完成練習。 3.複習:鞏固所學內容。 4.項目實踐:應用所學於實際項目中。這樣的結構化學習計劃能幫助你係統掌握Python並實現職業目標。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

Atom編輯器mac版下載
最受歡迎的的開源編輯器

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3漢化版
中文版,非常好用

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。