在python3中动态命名列表 [英] Dynamically naming list in python3

查看:133
本文介绍了在python3中动态命名列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想动态命名列表并使用它,我进行了很多搜索,但没有获得满意的答案.

I want to dynamically name the list and use that,I searched a lot but did not get the satisfactory answers how to do that.

if __name__=="__main__":

    lst_2017=[]
    lst_2018=[]
    lst_2019=[]


    for year in range(2017,2020):
        #avg_data is function which returns a list of number
        lst_"{}".format(year) = avg_data() 

错误:

 File "<ipython-input-84-4c1fefedd83e>", line 9
    lst_"{}".format(year) = avg_data()
           ^
 SyntaxError: invalid syntax

预期:

循环将迭代3次,函数将返回相应列表中的3个列表

loop will iterate 3 times and function return the 3 list in the respective lists

示例:

 lst_2017=[1,2,4]
 lst_2018=[3,4,5]
 lst_2019=[3,4,6]

推荐答案

使用字典而不是命名多个动态变量.这样,您所有的数据都将集中在一个数据结构中,并且可以从键/值对中轻松访问.

Use a dictionary instead of naming multiple dynamic variables. Then all your data is in one data structure and easily accessible from key/value pairs.

对于以下示例,我只需 zip 根据年份和数据一起构建字典,其中年份是键,平均值是值.

For the below example I simply zip up the years and data together to construct a dictionary, where years are the keys and averages are the values.

avg_data = [[1,2,4], [3,4,5], [3,4,6]]

result = {}
for year, avg in zip(range(2017, 2020), avg_data):
    result[year] = avg

print(result)

这也是可以做到的,因为 zip(range(2017,2020),avg_data)将给我们(year,avg)元组,可以是使用 dict()直接将其翻译成我们想要的字典:

Which can also be done like this, since zip(range(2017, 2020), avg_data) will give us (year, avg) tuples, which can be directly translated to our desired dictionary using dict():

result = dict(zip(range(2017, 2020), avg_data))

print(result)

输出:

{2017: [1, 2, 4], 2018: [3, 4, 5], 2019: [3, 4, 6]}

您可能必须对上述内容进行调整才能获得所需的结果,但这显示了总体思路.

You'll probably have to tweak the above to get your desired result, but it shows the general idea.

这篇关于在python3中动态命名列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆