2017-08-15 21 views
0

对Python来说很新,并且无法根据变量名来检查(或查找)如何检查数组。从Python中的变量名获取数组

如:

type = "world" 
world_arr = [] 
town_arr = [] 

#add to an array 
[type + '_arr'].append('test') <-- how? 
+0

'全局()[式+ '_arr']。追加( '试验')'?如果数组是全局/模块级变量 –

+0

我不太喜欢[链接重复问题](https://stackoverflow.com/questions/9437726/how-to-get-the-value-of-a-variable -given-其名-IN-A-字符串)。按名称查找变量几乎总是一个坏主意。问怎么做是一个经典的[XY问题](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。 –

回答

4

别看了变量名动态。这是一个主要的代码气味。使用字典。

lists = { 
    'world': [], 
    'town': [] 
} 

type = 'world' 
lists[type].append('test')