为什么 Python 告诉我在抽取随机样本之前进行排序?
Why does Python tell me to sort before taking a random sample?
Python 刚刚给了我奇怪的建议:
>>> import random
>>> random.sample({1: 2, 3: 4, 5: 6}, 2)
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
random.sample({1: 2, 3: 4, 5: 6}, 2)
File "C:\Users\*****\AppData\Local\Programs\Python\Python310\lib\random.py", line 466, in sample
raise TypeError("Population must be a sequence. For dicts or sets, use sorted(d).")
TypeError: Population must be a sequence. For dicts or sets, use sorted(d).
注意最后一行错误的第二部分。如果我稍后要随机化,为什么还要排序?好像在浪费 O(n log n) 时间。
来自cpython的提交历史-我的重点:github
In the future, the population must be a sequence. Instances of
:class:set
are no longer supported. The set must first be converted
to a :class:list
or :class:tuple
, preferably in a
deterministic order so that the sample is reproducible.
如果您不关心可重复性,则不需要排序。
Python 刚刚给了我奇怪的建议:
>>> import random
>>> random.sample({1: 2, 3: 4, 5: 6}, 2)
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
random.sample({1: 2, 3: 4, 5: 6}, 2)
File "C:\Users\*****\AppData\Local\Programs\Python\Python310\lib\random.py", line 466, in sample
raise TypeError("Population must be a sequence. For dicts or sets, use sorted(d).")
TypeError: Population must be a sequence. For dicts or sets, use sorted(d).
注意最后一行错误的第二部分。如果我稍后要随机化,为什么还要排序?好像在浪费 O(n log n) 时间。
来自cpython的提交历史-我的重点:github
In the future, the population must be a sequence. Instances of
:class:set
are no longer supported. The set must first be converted to a :class:list
or :class:tuple
, preferably in a deterministic order so that the sample is reproducible.
如果您不关心可重复性,则不需要排序。