随机

2012-09-05 49 views
0

鉴于照片列表生成前N个选择:随机

set 1 : 14 photos 
set 2 : 4 photos 
set 3 : 2 photos 

[{'set' : 1,'photos' : ['photo1','photo2'....'photo14']}, {'set' : 2,.....] 

我想显示10张图像给用户。我想要它,以便第一组是最有可能支配名单(比如,10个图像中的6个),而其他集合不是由于具有小数字而不公平地惩罚

什么是简单的鲁棒算法,导致这样美观的随机选择?

回答

4
import random 
photos = [{'set' : 1,'photos' : ['photo1','photo2'....'photo14']}, {'set' : 2,.....] 
weight = {1: 6, 2: 3, 3: 1} # set : number of shown photos 
show = [] 
for d in photos: 
    show.extend(random.sample(d['photos'], weight[d['set']])) 
random.shuffle(show) 
# show now contains a shuffled list of 6 photos from set 1, 3 from set 2 and 1 from set 3 
+1

酷 - 不知道关于random.sample –

+0

这是完美的,因为它的工作原理与体重告诉它一样 – aitchnyu