且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从集合中随机选择?Python

更新时间:2023-02-14 09:58:53

注意(2020 年 10 月): 从 v3.9 开始,Python 有 正式弃用 random.sample() 在集合上工作,官方指导是在传入之前将集合显式转换为列表或元组,但这并不能解决效率问题.

Note (Oct. 2020): as of v3.9, Python has officially deprecated random.sample() working on sets, with the official guidance being to explicitly convert the set to a list or tuple before passing it in, though this doesn't solve the efficiency problems.

>>> random.sample(set('abcdefghijklmnopqrstuvwxyz'), 1)
['f']

文档:https://docs.python.org/3/库/random.html#random.sample

请注意,无论您如何从集合中选择随机元素效率极低 - 它所花费的时间与集合的大小成正比,或者如果集合的底层哈希表由于稀疏而变得更糟删除元素.

Note that choosing random elements from a set is extremely inefficient no matter how you do it - it takes time proportional to the size of the set, or worse if the set's underlying hash table is sparse due to removed elements.

相反,您可能应该使用 不同的数据结构有效地支持此操作.

Instead, you should probably use a different data structure that supports this operation efficiently.