[英]How do I fix an "'int' object is not iterable" error in list function?
Here's my code:这是我的代码:
from random import random
for i in range(100):
a = list(int(random() * 100))
print(a)
and I keep getting this error message:我不断收到此错误消息:
TypeError: 'int' object is not iterable
What am I doing wrong?我究竟做错了什么? Please help me.请帮我。
In order to generate a list of 100 random numbers between 0 and 99, you'll have to either create the list first:为了生成 0 到 99 之间的 100 个随机数的列表,您必须先创建该列表:
from random import random
a = []
for _ in range(100):
a.append(int(random() * 100))
or use a list comprehension :或使用列表理解:
from random import random
a = [int(random() * 100) for _ in range(100)]
You haven't shown your expected output, but I presume you're looking for您没有显示您预期的 output,但我想您正在寻找
from random import random
for i in range(100):
a = [int(random() * 100)]
print(a)
You are trying to convert a type int
to type list
, which cannot be done.您正在尝试将类型int
转换为类型list
,这是无法完成的。 If you want to add your random number multiplied by 100
you can do the following.如果要添加随机数乘以100
,可以执行以下操作。
from random import random
random_numbers = []
for i in range(100):
random_numbers.append(int(random() * 100))
I'm trying to take 100 random numbers in a list.我正在尝试在列表中获取 100 个随机数。
You need to create a list and append the generated random numbers into it:您需要创建一个列表并将 append 生成的随机数放入其中:
import random
a = []
for i in range(100):
a.append(int(random.random() * 100))
print(a)
Note that you can also simply use random.randint
:请注意,您也可以简单地使用random.randint
:
(use random.randrange(0, 100)
or random.randint(0, 99)
if you don't want to include 100 as a possibility) (如果您不想包含 100,请使用random.randrange(0, 100)
或random.randint(0, 99)
)
import random
a = []
for i in range(100):
a.append(random.randint(0, 100))
print(a)
And you can simplify the whole thing by using a list comprehension:您可以通过使用列表推导来简化整个事情:
import random
a = [random.randint(0, 100) for __ in range(100)]
print(a)
(Using __
here as an ignored variable.) (在这里使用__
作为一个被忽略的变量。)
we can use random.sample(...) to get the numbers.我们可以使用 random.sample(...) 来获取数字。 sample() has 2 arguments: population or iterable, k= defines the number of samples we wanted to get. sample() 有 2 个 arguments:population 或 iterable,k= 定义我们想要获得的样本数。
sample() does not create duplicates, if duplicates are allowed.如果允许重复,则 sample() 不会创建重复。 we can also use choices() instead.我们也可以使用choices() 代替。
from random import sample
nums = list(map(lambda x: x * 100,sample(range(100), k=100)))
print(nums)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.