Python 如何在已存在的列表中存储随机数

Python 如何在已存在的列表中存储随机数,python,Python,假设我创建了一个列表-Names=John,Alex。我想为每个名字存储3个随机数,并找到这3个数字的平均值。您可以使用 import random inp_lst = ['John','Alex','Mathew'] n = len(inp_lst) # using list comprehension + randrange() # to generate random number list rand_lst = [random.randrange(1, 500, 1) for i

假设我创建了一个列表-Names=John,Alex。我想为每个名字存储3个随机数,并找到这3个数字的平均值。

您可以使用

import random

inp_lst = ['John','Alex','Mathew']
n = len(inp_lst)

# using list comprehension + randrange() 
# to generate random number list
rand_lst = [random.randrange(1, 500, 1) for i in range(n)]

mean_lst = sum(rand_lst)/n

res = []

for name,rand in zip(inp_lst,rand_lst):
    res += [[name,rand,mean_lst]]

print(res)

>>> [['John', 445, 429.0], ['Alex', 410, 429.0], ['Mathew', 432, 429.0]]

在这里,我们将为每个名称获取三个随机值,并使用基于列表的方法查找平均值(以相同的顺序)

随机导入
姓名=[“约翰”、“亚历克斯”]
#为每个名称创建一个包含三个随机数的新列表
rand=[[random.random()表示范围(3)]中的[in name]
#查找每个“内部列表”的平均值
平均值=[以兰特表示的x的总和(x)/len(x)]
打印(平均值)
例如,输出为:

[0.5319106811585387, 0.586153050082146]

你能把你试过的东西的代码贴出来吗?否则很难指导你。将这些随机数存储在你的名字列表中似乎是个坏主意。你为什么要这么做?创建一个随机数元组列表,或者创建一个以随机数元组作为值的dict(可能是比名称作为键更好的标识符,因为人们可能有重复的名称)。