JD12
JD12

Reputation: 35

How do i generate a random numbers for each integer in an array?

I want to generate random numbers for each integer of an array. For example, I have an array [4, 10, 15]. I want to generate 4 random numbers, 10 random numbers and 15 random numbers in python

Thanks in advance

Upvotes: 0

Views: 68

Answers (3)

Pratyush Behera
Pratyush Behera

Reputation: 123

Kindly go through this https://machinelearningmastery.com/how-to-generate-random-numbers-in-python/ you can solve almost all problems related to random.

Upvotes: 0

Joe Iddon
Joe Iddon

Reputation: 20414

The following generates a 2d list from a 1d list where each sub list has as many random numbers as the corresponding element in the 1d list, l.

import random
l = [4, 10, 15]
[[random.random()]*n for n in l]

Which, gives the following pretty-printed output:

[
  [
    0.9471464389026101,
    0.9471464389026101,
    0.9471464389026101,
    0.9471464389026101
  ],
  [
    0.7127486495769667,
    0.7127486495769667,
    0.7127486495769667,
    0.7127486495769667,
    0.7127486495769667,
    0.7127486495769667,
    0.7127486495769667,
    0.7127486495769667,
    0.7127486495769667,
    0.7127486495769667
  ],
  [
    0.5239644545312407,
    0.5239644545312407,
    0.5239644545312407,
    0.5239644545312407,
    0.5239644545312407,
    0.5239644545312407,
    0.5239644545312407,
    0.5239644545312407,
    0.5239644545312407,
    0.5239644545312407,
    0.5239644545312407,
    0.5239644545312407,
    0.5239644545312407,
    0.5239644545312407,
    0.5239644545312407
  ]
]

Upvotes: 0

iElden
iElden

Reputation: 1280

import random

array = [4, 10, 15]

result = [[random.randint(YOUR_MIN_NUMBER, YOUR_MAX_NUMBER) for _ in range(i)] for i in array]

Output:

[[4, 4, 5, 3], [7, 7, 7, 6, 3, 6, 3, 6, 8, 9], [6, 3, 6, 4, 1, 3, 5, 10, 3, 10, 7, 9, 1, 3, 1]]

Upvotes: 1

Related Questions