简体   繁体   中英

Why does Python tell me to sort before taking a random sample?

Python just gave me weird advice:

>>> 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).

Note the second part of the last error line. Why should I sort if I'm going to randomize a moment later anyway? Seems like wasting O(n log n) time.

From the commit history of cpython - My emphasis: 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.

If you don't care about reproducibility sorting is not necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM