Python中的动态变量 [英] Dynamic variable in Python
问题描述
例如,如何在python中创建具有动态名称的列表
How can I create lists with dynamic names in python, for example
for i in range(len(myself)):
list(i) = []
我应该用什么代替list(i)? 这意味着我想要一些名字,如下所示:
what should I use instead of list(i) ? it means that i want some names as below:
list1
list2
list3
...
推荐答案
我建议您只使用列表或字典,而不要使用动态变量名.下面的所有版本都会导致lists[0]
,lists[1]
等为[]
,这似乎与您想要的内容足够接近,并且从长远来看将更具可读性/可维护性. (注意:我使用lists
而不是list
作为变量名,因为后者会覆盖内置的list
函数,您可能不希望这样做).
I'd advise you to just use a list or dictionary instead of dynamic variable names. All the versions below result in lists[0]
, lists[1]
etc being []
, which seems close enough to what you want, and will be more readable/maintainable in the long term. (Note: I'm using lists
instead of list
as a variable name because the latter would overwrite the builtin list
function, which you probably don't want).
1)版本,其中lists
是列表列表(数字只是列表的顺序):
1) Version with lists
being a list of lists (the numbers are just the order of the lists):
lists = [[] for i in range(len(myself))]
2)相同,但是具有for循环而不是列表理解:
2) Same but with a for loop instead of a list comprehension:
lists = []
for i in range(len(myself)):
lists.append([])
3)版本为lists
是包含数字作为键的列表的字典(如果您以后要删除某些值,则更加灵活):
3) Version with lists
being a dictionary of lists with numbers as keys (a bit more flexible if you want to remove some of the values later or such):
lists = {}
for i in range(len(myself)):
lists[i] = []
关于动态变量名,即像list1
而不是lists[1]
这样的变量...说真的,您可能不应该这样做.它不必要地复杂且难以维护.考虑一下-下个月,您将要修改脚本,然后尝试找出变量list1
的定义位置,而纯文本搜索将无法做到这一点.这很痛苦.
但是,如果您确实出于某些原因想要这样做,可以通过exec
-此处有一些原因不使用它-或修改locals()
-不好根据文档的想法.另请参阅评论,以获取更多讨论,讨论为什么这些东西不是一个好主意,甚至甚至在谈论这些问题时都令人困惑.
About dynamic variable names, i.e. variables like list1
instead of lists[1]
... Seriously, you probably shouldn't do that. It's unnecessarily complicated and hard to maintain. Think about it - next month you'll want to modify the script, and you'll try to figure out where the variable list1
was defined, and you won't be able to do that with a plain text search. It's a pain.
But if you really want to for some reason, it's possible with exec
- here are some reasons not to use it - or with modifying locals()
- bad idea according to documentation. Also see comments for more discussion on why these things are a bad idea and how confusing it gets even talking about them.
这篇关于Python中的动态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!