Home > database >  Generate 3 random lists and create another one with the sum of their elements
Generate 3 random lists and create another one with the sum of their elements

Time:10-22

I want to create a NxN matrix (represented as lists of lists), where the first n-1 columns have random numbers in the range 1 to 10, and the last column contains the result of adding the numbers in previous commons.

import random
randomlist1 = []
for i in range(1,10):
    n = random.randint(1,100)
    randomlist1.append(n)
print(randomlist1)

randomlist2 = []
for i in range(1,10):
    n = random.randint(1,100)
    randomlist2.append(n)
print(randomlist2)

randomlist3 = []
for i in range(1,10):
    n = random.randint(1,100)
    randomlist3.append(n)
print(randomlist3)

# I have problems here

lists_of_lists = [sum(x) for x in (randomlist1, randomlist2,randomlist3)]
[sum(x) for x in zip(*lists_of_lists)]
print(lists_of_lists)

CodePudding user response:

IIUC try with numpy

import numpy as np
np.random.seed(1) # just for demo purposes 
# lists comprehensions to create your 3 lists inside a list
lsts = [np.random.randint(1,100, 10).tolist() for i in range(3)]
np.sum(lsts, axis=0) 
# array([145, 100, 131, 105, 215, 115, 194, 247, 116,  45])

lsts

[[38, 13, 73, 10, 76, 6, 80, 65, 17, 2],
 [77, 72, 7, 26, 51, 21, 19, 85, 12, 29],
 [30, 15, 51, 69, 88, 88, 95, 97, 87, 14]]

CodePudding user response:

Based on @It_is_Chris answer, I propose this as a numpy only implementation, without using lists:

np.random.seed(1)

final_shape = (3, 10)
lsts = np.random.randint(1, 100, np.prod(final_shape)).reshape(final_shape)
lstsum = np.sum(lsts, axis=0)
  • Related