在python3中动态命名列表

编程入门 行业动态 更新时间:2024-10-28 02:24:18
本文介绍了在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中动态命名列表

本文发布于:2023-06-08 14:31:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/583111.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:动态   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!