#! /Usr/bin/env python #-*-Coding: UTF-8 -*- # Python2.7x # Random_weight.py # Author: orangleliu@gmail.com ''''' Each element has a weight, and then random values are obtained based on the weight. Enter {"A": 2, "B": 2, "C": 4, "D": 10, "E": 20} Output A Value ''' Import random Import collections as coll Data = {"A": 2, "B": 2, "C": 4, "D": 6, "E": 11} # The first method is to put each element's weight element into an Array Based on the element's Weight Value "A" * 2..., and then obtain the weight by the maximum array subscript and random number. 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] # The second method is to calculate the sum of weights, retrieve a random number, traverse all elements, and add weights to sum. When sum is greater than or equal to a random number, stop and retrieve the current tuples. 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 ()") |