如何从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屋!