Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a 2D array with random numbers WITHOUT NUMPY (Python)

How can I create a 2D array with random numbers without using NumPy (Python)

like image 693
tjardskleener Avatar asked Nov 26 '25 02:11

tjardskleener


2 Answers

You could use the random module and populate a nested list with a list comprehension

import random

low = 0
high = 10
cols = 10
rows = 5

[random.choices(range(low,high), k=cols) for _ in range(rows)]

[[5, 7, 1, 0, 6, 5, 9, 2, 5, 6],
 [9, 2, 3, 0, 6, 7, 0, 6, 6, 3],
 [2, 7, 9, 2, 4, 5, 5, 9, 9, 4],
 [2, 6, 7, 8, 5, 1, 4, 4, 4, 4],
 [9, 2, 8, 4, 5, 2, 0, 1, 2, 1]]

For a nested list of floats, you can map each range with float:

choices = list(map(float, range(low,high)))
[random.choices(choices , k=cols) for _ in range(rows)]

[[0.0, 3.0, 9.0, 1.0, 5.0, 3.0, 7.0, 4.0, 2.0, 4.0],
 [5.0, 8.0, 7.0, 7.0, 7.0, 2.0, 9.0, 8.0, 2.0, 6.0],
 [3.0, 3.0, 1.0, 9.0, 2.0, 8.0, 7.0, 2.0, 9.0, 7.0],
 [7.0, 8.0, 1.0, 2.0, 0.0, 6.0, 7.0, 6.0, 0.0, 9.0],
 [3.0, 3.0, 3.0, 1.0, 7.0, 8.0, 3.0, 9.0, 2.0, 8.0]]
like image 59
yatu Avatar answered Nov 27 '25 17:11

yatu


[[random.random() for _ in range(3)] for _ in range(7)]

This generates a 2D array of size [7, 3] with random float in [0, 1) interval.

You use nested list comprehensions. The outer one builds a main list while the inner one builds lists that are used as elements of the main list.


Edit

You can then tweak it for your needs. For example:

import random
import pprint

NUM_ROWS=7
NUM_COLS=3
MAX_VAL=1000.50
MIN_VAL=-MAX_VAL

pprint.pprint([
  [random.uniform(MIN_VAL, MAX_VAL) for _ in NUM_COLS]
  for _ in NUM_ROWS
])

This prints a list/array/matrix of 7 lines and 3 colums with random floats in [-1000.50, 1000.50) interval:

[[561.3985362160208, -157.9871329592354, -245.7102502320838],
 [-817.8786101352823, -528.9769041860632, 102.67728824479877],
 [-886.6488625065194, 941.0504221837489, -458.58155555154565],
 [6.69525238666165, 919.5903586746183, 66.70453038938808],
 [754.3718741592056, -121.25678519054622, -577.7163532922043],
 [-352.3158889341157, 254.9985130814921, -365.0937338693691],
 [563.0633042715097, 833.2963094260072, -946.6729221921638]]

The resulting array can be indexed with array[line][column].

like image 39
AlexisBRENON Avatar answered Nov 27 '25 15:11

AlexisBRENON



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!