Create empty list names using a loop [duplicate]

混江龙づ霸主 提交于 2019-12-25 18:12:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!