问题
Beginner's question.
I want to create several empty lists and name them. Currently I am doing it the foolproof but cumbersome way,
size_list=[]
type_list=[]
floor_list=[]
I am trying to do it less cumbersome,
for item in ['size', 'type']:
item+'_list'=[]
however, this results in the following error,
item+'_list'=[]
^
SyntaxError: can't assign to operator
Can this be fixed easily, or should I use another method to create empty lists with names?
回答1:
If you have lots of data to track in separate variables, don't rely on related variable names. What will your code do with all these variables after you have defined them? Use a dictionary:
datalists = dict()
for item in ['size', 'type']:
datalists[item] = []
Addendum:
By using a dictionary, you have one variable containing all list values (whatever they are) for your different labels. But perhaps (judging from your choice of names) the values in the corresponding list positions are meant to go together. E.g., perhaps size_list[0]
is the size of the element with type type_list[0]
, etc.? In that case, a far better design would be to represent each element as a single tuple, dict or
object of a custom class, and have a single list of all your objects.
Thing = namedtuple("Thing", ['size', 'type', 'floor'])
spoon = Thing(size=33, type='spoon', floor='green')
things = []
things.append(spoon)
Tuples (named or otherwise) cannot be modified, so this might not be what you need. If so, use a dictionary instead of a tuple, or write a simple class.
来源:https://stackoverflow.com/questions/42768213/create-empty-list-names-using-a-loop