Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

list - Dynamic variable in Python


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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) 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) Same but with a for loop instead of a list comprehension:

lists = []
for i in range(len(myself)):
   lists.append([])

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] = []

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...