简体   繁体   English

从范围中选择randint

[英]Selecting randint from range

from random import randint
number_of_trials = 100
range_of_random_numbers = 1000
for each in number_of_trials:
    print randint(range(range_of_random_numbers))

I am a beginner to python. 我是python的初学者。 When I try running the above code I get the error: 当我尝试运行上面的代码时,我收到错误:

TypeError: 'int' object is not iterable TypeError:'int'对象不可迭代

I'm trying to get a random number from a range (defined in range_of_numbers) to print a certain amount of times (defined in number_of_trials). 我试图从范围(在range_of_numbers中定义)中获取一个随机数来打印一定数量的时间(在number_of_trials中定义)。 Please help, what am I doing wrong? 请帮忙,我做错了什么?

Use range to make an iterable (list if you're using Python 2.x) which will be used for iteration. 使用range来创建一个可迭代的(如果你使用Python 2.x,则列表)将用于迭代。

and you need to pass two integer to random.randint , not an interable (or list): 你需要将两个整数传递给random.randint ,而不是一个interable(或list):

from random import randint

number_of_trials = 100
range_of_random_numbers = 1000
for each in range(number_of_trials):
    print randint(0, range_of_random_numbers)

I think what you want to use is choice. 我想你想要用的是选择。

from random import choice

Then change 然后改变

print randint(range(range_of_random_numbers))

to

print choice(range(range_of_random_numbers))

The choice function will randomly pick an element from a non-empty sequence. 选择函数将从非空序列中随机选择一个元素。

One issue and one suggestion in your code - 您的代码中有一个问题和一个建议 -

  1. You are doing - for each in number_of_trails: - this is wrong, you are trying to iterate over an integer, you should do - for each in range(number_of_trails): . 你正在做 - for each in number_of_trails: - 这是错误的,你试图迭代一个整数,你应该做 - for each in range(number_of_trails):

  2. The best to use here is random.choice() (Instead of randint() ). 这里最好用的是random.choice() (而不是randint() )。 Especially if the range_of_random_numbers is not continuous. 特别是如果range_of_random_numbers不连续。

Example - 示例 -

from random import choice
number_of_trials = 100
range_of_random_numbers = 1000
for each in range(number_of_trials):
    print choice(range(range_of_random_numbers))

From documentation of random.choice() - random.choice()文档 -

Return a random element from the non-empty sequence seq. 从非空序列seq返回一个随机元素。

It should be like 应该是这样的

from random import randint
number_of_trials = 100
range_of_random_numbers = 1000
for each in range(number_of_trials):
    print randint(range(range_of_random_numbers))

You got the error due to the fact int object are not iterable that is : 由于int对象不可迭代,因此得到错误:

ie) 即)

for a in 1:
    print a

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

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

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