首页 > 解决方案 > 在 Python 中将函数结果保存为连续的列表名称?

问题描述

我想生成 4 个从 1 到 50 的随机数。我想定义这个随机代码生成器的函数 n 次。并将每个随机 4 个数字保存在一个连续的列表名称中。

def eko():
    print(random.sample(range(1, 50), 4))

def eko_times(times):
    for i in range(times):eko()

例如,当我输入时,eko_times(2)我想看到这个结果:

eko_1:[1,43,23,3]
eko_2:[8,32,34,2]

如何将此输出另存为 eko_i 的新列表名称?

标签: pythonlistoutput

解决方案


内联评论

def eko_times(times, low, high, n):
    out = [] # list for collecting results
    for _ in range(times): # you don't need the value of i
        out.append(random.sample(range(low, high+1), n))
    return out

现在您可以访问单个结果

>>> results = eko_times(3, 1, 50, 4)    
>>> results[0]
[10, 40, 11, 25]

推荐阅读