动态创建变量(对于列表) [英] Dynamic creation of variables (for Lists)
问题描述
我知道这可能是一个坏主意..但似乎是在创建所有可能的选项并忽略未使用的结果之外执行此操作的最佳"方法.我有一个源文件,其中包含来自 12 个潜在值的值.
I know this is likely a bad idea.. but seems the "best" way to do this outside of creating all possible options and ignore the unused results. I have a source file that contains values from 12 potential values.
我已经在列表中包含了所有必需的字符串,但是我的目标是让每个字符串成为列表本身的开头,如果这有意义的话?
I have all the required strings within a list already however I'm aiming to make each string the start of an list itself if this makes any sense?
例如当前列表包含 "a,b,c,d,e" 循环中所需的输出将是 'a=[].. b=[]' 等
For example the current list contains "a,b,c,d,e" the required output in the loop would be 'a=[].. b=[]' etc.
推荐答案
假设您的意思不是列表的开始",而是列表的名称"(正如您的代码所建议的那样)......是的,这是一个坏主意.您可能应该使用 dict
代替,例如
Assuming you mean not "the start of a list", but "the name of a list" (as your code would suggest)... yes, this is a bad idea. You should probably use a dict
instead, something like
d = {var_name: [] for var_name in current_list}
实际上这就是 Python 在幕后所做的.当你写
Actually this is kind of what Python does behind the scenes. When you write
a = []
然后 Python 将条目 a: []
添加到(基本上等同于)dict
.您可以使用 globals()
函数(如果在模块范围内)或 locals()
(如果在函数内部)查看字典中的内容.
then Python is adding an entry a: []
to (something basically equivalent to) a dict
. You can see what's in that dictionary using the globals()
function if at module scope, or locals()
if inside a function.
这篇关于动态创建变量(对于列表)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!