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
.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.