红糖糍粑
因此,为每个ID1生成一个累积分布函数:cdfs = defaultdict()for id1,id2,val in d: prevtotal = cdfs[id1][-1][0] newtotal = prevtotal + val cdfs[id1].append( (newtotal,id2) )所以你会有cdfs = { 701 : [ (0.2,1), (0.5,2), (1.0,3) ], 702 : [ (0.2,1), (0.5,2) ], 703 : [ (0.5,3) ] }然后生成一个随机数并在列表中搜索。def func(id1): max = cdfs[id1][-1][0] rand = random.random()*max for upper,id2 in cdfs[id1]: if upper>rand: return id2 return None