如何从 Python 集中挑选 2 个随机项目? [英] How do I pick 2 random items from a Python set?
问题描述
我目前有一个大小为 n 的 Python 集,其中 n >= 0.是否有一个快速的 1 或 2 行 Python 解决方案来做到这一点?例如,该集合将如下所示:
I currently have a Python set of n size where n >= 0. Is there a quick 1 or 2 lines Python solution to do it? For example, the set will look like:
fruits = set(['apple', 'orange', 'watermelon', 'grape'])
目标是从上面随机挑选 2 个项目,上面的集合可能包含 0、1 或多个项目.我能想到的唯一方法是将集合转换为列表(可变),从中我可以访问集合长度内的 2 个随机唯一索引.
The goal is to pick 2 random items from the above and it's possible that the above set can contain 0, 1 or more items. The only way I can think of doing the above is to convert the set to a list(mutable) from where I can access 2 random unique index within the length of the set.
推荐答案
使用 random
模块:http://docs.python.org/library/random.html
import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)
这对两个值进行采样,没有替换(所以这两个值是不同的).
This samples the two values without replacement (so the two values are different).
这篇关于如何从 Python 集中挑选 2 个随机项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!