2012-04-12 58 views
9

我有這樣一本字典:如何隨機選擇多個鍵和字典中的蟒蛇值

user_dict = { 
      user1: [(video1, 10),(video2,20),(video3,1)] 
      user2: [(video1, 4),(video2,8),(video6,45)] 
      ... 
      user100: [(video1, 46),(video2,34),(video6,4)]     
      } 

(video1,10) means (videoid, number of request) 

現在我想隨機選擇10個用戶,並做一些計算像

1. calculate number of videoid for each user. 
2. sum up the number of requests for these 10 random users, etc 

那麼我需要增加隨機數到20,30,40分別

但是「random.choice」一次只能選擇一個值,對嗎?如何選擇多個鍵和每個鍵後面的列表?

回答

17

這就是random.sample()是:

Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.

這可以用來選擇鍵。這些值可以隨後通過正常字典查找來檢索:

>>> d = dict.fromkeys(range(100)) 
>>> keys = random.sample(list(d), 10) 
>>> keys 
[52, 3, 10, 92, 86, 42, 99, 73, 56, 23] 
>>> values = [d[k] for k in keys] 

或者,可以直接從d.items()採樣。

+0

如果你想獲得鍵和值,你可以在''dict.items()''''上使用''random.sample()'',而不是獲得一個鍵然後進行查找。 – 2012-04-12 14:29:21

+1

你需要列表(d)或者你會得到這個錯誤 raise TypeError(「人口必須是一個序列或集合,對於字典,使用列表(d)。」) TypeError:人口必須是一個序列或集合。對於字典,請使用列表(d)。 – 2016-04-21 15:34:00