-1

Consider the following loop:

import random
 
for m in range(0,2):
    rand_list=[]
    n=10
    for i in range(n):
        rand_list.append(random.randint(3,9))
    print(rand_list)

That outputs two lists as:

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

How can I possibly label them with the dummy variable m define in the loop, for example lst[0],lst[1] or such, in order to compose the mean result

lst_mean = lst[0]+lst[1]/2

or similar quantities?

Note I know that the indexing here is not correct. The idea is that in the end of the loop for each m I define a list labeled by m and contains the corresponding result of rand_list.

Marion
  • 271
  • 3
  • 11

1 Answers1

1

You need a list of lists.

import random

lst = []
for m in range(2):
    rand_list = []
    n = 10
    for i in range(n):
        rand_list.append(random.randint(3, 9))
    lst.append(rand_list)

print(lst)

Example output:

[[5, 7, 9, 7, 8, 9, 9, 5, 3, 9], [8, 8, 5, 7, 7, 9, 8, 7, 4, 7]]

Now you can calculate the mean result.

result = [sum(values) / len(values) for values in zip(*lst)]
print(result)

Output

[6.5, 7.5, 7.0, 7.0, 7.5, 9.0, 8.5, 6.0, 3.5, 8.0]

If you want more lists you can change the 2 in for m in range(2): to a different number.

Matthias
  • 12,873
  • 6
  • 42
  • 48
  • I think what OP wants is dynamic variable assignment. Something like this https://stackoverflow.com/a/6181959/14196135 Judging from the comments. – Josip Juros Jun 06 '22 at 13:04
  • 3
    Maybe. But that's a really, really, really bad idea. No sane programmer would use this if it's not for some kind of weird meta-programming. That's the reasons why other datastructures like a list exist. – Matthias Jun 06 '22 at 13:07
  • Or in this case a dictionary does exactly whats needed in a very good way. – Josip Juros Jun 06 '22 at 13:09
  • As a mathematician I indeed would think I need a dynamic variable but I think that @Matthias answer is something I can work with. – Marion Jun 06 '22 at 13:09
  • @Marion Then dynamic variables and dictionaries and a list of lists works. Take your pick – Josip Juros Jun 06 '22 at 13:10
  • 1
    @Marion then why not use a NxM matrix with numpy? You preallocate the matrix full of zeros, at each iteration you fill one row `mat[row,:] = list` and then you can use `numpy.mean()` to calculate the mean, with the extra that you can select which axis to perform the reduction. – Fra93 Jun 06 '22 at 13:11