隨機

2012-09-05 48 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