简体   繁体   English

随机模块没有属性“选择”

[英]Random Module has not attribute 'choices'

I am using Sublime Text3.我正在使用 Sublime Text3。 I am encountering a problem with the choices attribute with the random module.我遇到了random模块的choices属性问题。 I do not have the same name in any path or directory.我在任何路径或目录中都没有相同的名称。 The other attributes of random work just fine.随机工作的其他属性就好了。

import random
import string

letters = string.ascii_lowercase
print(letters)
gen = random.choices(letters, k=16)
print(gen)

Here is the error code:这是错误代码:

abcdefghijklmnopqrstuvwxyz
Traceback (most recent call last):
  File "/home/anon/.config/sublime-text-3/Packages/User/test.py", line 6, in <module>
    gen = random.choices(letters)
AttributeError: 'module' object has no attribute 'choices'

What are the common causes of this problem?这个问题的常见原因是什么?

There's no random.choices in Python 2. You can use random.sample in Python 2. Python 2 中没有random.choices 。您可以在 Python 2 中使用random.sample

gen = random.sample(letters, k=16)

random.choices is included in Python 3 random.choices包含在 Python 3

It would seem you are using a version of Python that is older than 3.6 which is when random.choices was introduced.看起来您使用的 Python 版本早于引入random.choices的 3.6 版本。 You can see it listed at the bottom of this function description here您可以在此 function 描述的底部 看到

You can verify your version by running您可以通过运行验证您的版本

import sys
sys.version

I encountered the same error when I used Python 2.7.我在使用 Python 2.7 时遇到了同样的错误。

As a workaround, I simply used random.choice instead of random.choices , in a way as作为一种解决方法,我只是使用random.choice而不是random.choices ,在某种程度上

foo = [random.choice(my_list) for _ in range(50)]

Although we do not have random.choices in Python 2.7, we have random.choice (the former is multiple choices with duplicates, while the latter single choice).虽然我们在 Python 2.7 中没有random.choices ,但我们有random.choice (前者是重复的多选,而后者是单选)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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