1

I would like to create a list that is 100 elements long but each element is 30 long. The elements with a length of 30 would be made up of random numbers from [0,1] excluding 1.

I'm thinking I need a for loop or some sort of append.

My expected outcome would be something like:

[Random numbers between 0-1 excluding 1, Random numbers between 0-1 excluding 1, Same here,..., and the same idea here. ]

quamrana
  • 37,849
  • 12
  • 53
  • 71
pckofwolfs
  • 83
  • 2
  • 2
  • 9
  • 2
    Can you edit the question and add the code you've come up with so far? – Håken Lid Jun 27 '18 at 13:57
  • I'm not sure what your expected output is. You want a nested list? A list of length 100 containing lists of length 30 containing numbers? – Aran-Fey Jun 27 '18 at 14:03

3 Answers3

1

I would suggest using numpy, then you can avoid nested loops and append statements. Try something like this:

import numpy as np
random_matrix = np.random.rand(100,30)
Bogdan Osyka
  • 1,943
  • 3
  • 14
  • 16
  • This would create a list with 30 elements of length 30 right? – pckofwolfs Jun 27 '18 at 14:01
  • @ pckofwolfs I have edited my comment. This, would create a numpy array with 100 elements, each of length 30, which is pretty much the same as python list, but implemented in a more compact way: https://stackoverflow.com/questions/993984/why-numpy-instead-of-python-lists – Bogdan Osyka Jun 27 '18 at 14:03
  • so to use this in my purpose I would want to have 30,100 then? – pckofwolfs Jun 27 '18 at 14:09
  • @pckofwolfs no, it should be as written in my comment. It will create an array of 100 elements, where each element has the size of 30. (30, 100) will create an array of 30 elements, each with the size of 100 – Bogdan Osyka Jun 27 '18 at 14:11
  • Okay, thank you for your time and responses. I forgot I can size my list's in different ways. – pckofwolfs Jun 27 '18 at 14:11
  • @pckofwolfs My pleasure – Bogdan Osyka Jun 27 '18 at 14:12
1

Simply use list comprehension and random.uniform function:

 import random
 expected_list = [[random.uniform(0,1) for i in range(30)] for j in range(100)]
 print(expected_list)
Taohidul Islam
  • 5,246
  • 3
  • 26
  • 39
  • Doesn't `random.random()` already returns values in the interval [0,1.0) ? Is there any difference when using `random.random` and `random.uniform(0,1)` when working with the [0,1) interval ? – HolyDanna Jun 27 '18 at 14:05
0
import random
list = [[random.uniform(0, 0.9999999999999999) for y in range(30)] for x in range(100)]
print(list)
jalanga
  • 1,456
  • 2
  • 17
  • 44