Turning random.random () result into a list - Python

I am trying to create a list that extracts ten random real numbers between 30 and 35 and prints them in a list. When I run the code below, I get the following error:

TypeError: The "float" object is not iterable.

Here is the code:

lis = list(range(10)) random.seed(70) for i in range(0, len(lis)): randreal = (random.random()*5 + 30) lis = list(randreal) print(lis) 

I feel like I'm missing something obvious. When I run the code without

 lis=list(randreal) print(lis) 

I get the results I want, just not on the list. Also I'm trying to do this without random.uniform

+5
source share
2 answers

First you created the lst list [0,1,2,3,4,5,6,7,8,9]. It's not needed. Then you try to overwrite this lst list with a new list(randreal) that throws an error because its list constructor is invalid

You can start with an empty list and add each arbitrary number that you created:

 lis = [] random.seed(70) for i in range(10): randreal = (random.random()*5 + 30) lis.append(randreal) print(lis) 

or overwrite each value of the original list with a new random value

 lis = list(range(10)) random.seed(70) for i in range(0, len(lis)): randreal = (random.random()*5 + 30) lis[i] = randreal print(lis) 
+3
source

You write:

 lis = list(randreal) 

But list(..) is the constructor here. The constructor is looking for an iterable object (another list, set, dictionary, generator, etc.), which can turn into a list. A floating point is not iterable, so a list cannot be created for it. This will result in an error.

One way to solve it is to assign the list index to lis :

 lis = [0] * 10 random.seed(70) for i in range(0, len(lis)): randreal = (random.random()*5 + 30) lis [i] = randreal # assign to an index print(lis) 

But this is still not very elegant: first you create a list, and then modify it. You can improve the code by drawing 10 elements and each time .append(..) to the list:

 lis = [] random.seed(70) for i in range(0, 10 ): randreal = (random.random()*5 + 30) lis .append( randreal ) # append to the list print(lis) 

This is better, but still with a lot of code, so we can use list comprehension to make it more declarative:

 random.seed(70) lis = [random.random()*5 + 30 for _ in range(10)] print(lis) 
+6
source

Source: https://habr.com/ru/post/1271264/


All Articles