使用循环创建空列表名称 [英] Create empty list names using a loop

查看:116
本文介绍了使用循环创建空列表名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

初学者的问题.

我想创建几个空列表并命名.目前,我正在这样做,但很麻烦,

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

我正在尝试减少麻烦,

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?

推荐答案

如果要在单独的变量中跟踪大量数据,请不要依赖于相关的变量名.定义完所有这些变量后,您的代码将如何处理?使用字典:

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

附录: 通过使用字典,您将拥有一个变量,其中包含不同标签的所有列表值(无论它们是什么).但是也许(从您选择的名称来看)相应列表位置中的值是要组合在一起的.例如,也许size_list[0]是类型为type_list[0]的元素的大小等?在这种情况下,更好的设计是将每个元素表示为单个元组,字典或 自定义类的对象,并具有所有对象的单个列表.

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.

这篇关于使用循环创建空列表名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆