TypeError:randint()得到了一个意外的关键字参数' low'

时间:2016-09-15 04:54:17

标签: python python-2.7 random

names = ['Bob', 'Jessica', 'Mary', 'John', 'Mel']
import random
random.seed(500)
random_names = [names[random.randint(low = 0, high = len(names))] for i in range(1000)]

目标是使用上述五个随机列出1,000个名字。但上面的代码会抛出以下错误:

Traceback (most recent call last):
  File "<pyshell#88>", line 1, in <module>
    random_names = [names[random.randint(low = 0, high = len(names))] for i in range(1000)]
TypeError: randint() got an unexpected keyword argument 'low'

2 个答案:

答案 0 :(得分:2)

删除lowhigh,您的代码将正常运行。即random.randint(0, len(names)-1)

然而,更有效的方法是使用random.choice()

>>> [random.choice(names) for i in range(10)]
['Mel', 'Mary', 'Mary', 'John', 'Bob', 'Mel', 'John', 'Jessica', 'Jessica', 'John']

答案 1 :(得分:0)

(导入numpy会这样做)

将numpy导入为np

np.random.seed(500)

random_names = [names [np.random.randint(low = 0,high = len(names))] for i in

范围(1000)]

打印前10条记录

random_names [:10]

(结果如下)

缺货[8]: ['玛丽',  “杰西卡”,  “杰西卡”,  “鲍勃”,  “杰西卡”,  “杰西卡”,  “杰西卡”,  '玛丽',  '玛丽',  '玛丽']