gpt4 book ai didi

python - 如何在字典python中随机选择多个键及其值

转载 作者:太空狗 更新时间:2023-10-29 17:26:00 26 4
gpt4 key购买 nike

我有这样一本字典:

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”一次只能选择一个值,对吧?如何选择多个键以及每个键后面的列表?

最佳答案

这就是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() 中采样。

关于python - 如何在字典python中随机选择多个键及其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10125568/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com