Linux 如何在python中的arraylist中存储变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6081174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 04:11:29  来源:igfitidea点击:

How to store variables in arraylist in python

pythonlinux

提问by Mahakaal

I want to have something like

我想要类似的东西

var1 = ('a','b','c')
var2 = ('a1','b1','c1')
var3 = ('a2','b2','c2')
var4 = ('a3','b4','c5')
var5 = ('a6','b6','c6')

How can i have all those in one variable var

我如何将所有这些都放在一个变量 var 中

I have a loop which will be saving each array but i want to have only one variable

我有一个循环将保存每个数组,但我只想有一个变量

采纳答案by phihag

var = [var1, var2, var3, ('a3', 'b4', 'c5'), var5]

You could also copy variin a loop, but that's very bad programming practice. Basically, you should construct a list upfront and not later from variable names. If you must do it, here's how:

您也可以在循环中复制 var i,但这是非常糟糕的编程习惯。基本上,您应该预先构建一个列表,而不是稍后从变量名称构建。如果您必须这样做,请执行以下操作:

var = [locals()['var' + str(i)] for i in range(6)]

This is the longer form of:

这是更长的形式:

var = []
for i in range(6):
    var.append(locals()['var' + str(i)])