当前位置: 代码迷 >> 综合 >> python2 python3 random.sample区别:TypeError: Population must be a sequence or set. For dicts, use lis
  详细解决方案

python2 python3 random.sample区别:TypeError: Population must be a sequence or set. For dicts, use lis

热度:11   发布时间:2023-12-15 16:20:18.0

报错:TypeError: Population must be a sequence or set. For dicts, use list(d).

完整报错:

>>> random.sample(a.values(),1)
Traceback (most recent call last):File "<stdin>", line 1, in <module>File "/home/user1/miniconda3/envs/py377/lib/python3.7/random.py", line 317, in sampleraise TypeError("Population must be a sequence or set. For dicts, use list(d).")
TypeError: Population must be a sequence or set.  For dicts, use list(d).

妈的这鬼错误是因为python2和python3的区别,在python2中对dict的values进行随机采样就没有问题,python3就不行:

(对dict的keys随机采样都没有问题)

py2:

$ python2
Python 2.7.18 (default, Aug  4 2020, 11:16:42)
[GCC 9.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import random
>>> a = {
    'a':3,'b':4}
>>> random.sample(a.values(),1)
[3]

py3

$ python
Python 3.7.7 (default, Mar 26 2020, 15:48:22)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = {
    'a':3,'b':4}
>>> import random
>>> random.sample(a.values(),1)
Traceback (most recent call last):File "<stdin>", line 1, in <module>File "/home/user1/miniconda3/envs/py377/lib/python3.7/random.py", line 317, in sampleraise TypeError("Population must be a sequence or set. For dicts, use list(d).")
TypeError: Population must be a sequence or set.  For dicts, use list(d).
  相关解决方案