如何用python批量生成变量/数组 How to define a batch of regular variables in python

【问题情境 Situation】

现在需要生成一系列数组变量形如a_1=[], a_2=[], a_3=[], ... , a_n=[],之所以不能用二维数组是因为这些list的长度在之后使用过程中并不相同,index也不一致,不方便计算

Assuming a series of variables like a_1=[], a_2=[], a_3=[], ... , a_n=[] need to be defined. Here it's not allowed to use 2-dimensional list or DataFrame, cause these lists have various length and index, a 2-d list won't work.

【解决方法 Solution】

这个方法以前我在matlab中屡试不爽,但在python中找了一会才找到这个函数,即,将字符串作为可执行代码执行的exec()。这是一个python内置函数,不需要导入其他toolkit,可以参考官方文件理解exec()

It took me a while to find this function in python, exec(), which executes strings as executable code. This is a python built-in function, you can refer to the official document to understand it. exec()

【示例 Example】

# 假设我们如【问题情境】中所描述,生成5个空数组,命名规律为a_1, a_2, a_3, a_4, a_5
# As described in [Situation], let's define 5 empty lists and name them a_1, a_2, a_3, a_4, a_5
for i in range(1,6):
    exec('a_'+str(i)+'=[]')

需要注意的是括号内一定要构成一个完整的字符串,否则无法执行

Note that the code in parentheses must form a complete string or it will not work

你可能感兴趣的:(如何用python批量生成变量/数组 How to define a batch of regular variables in python)