简体   繁体   English

从Python列表中的项目创建新的空列表?

[英]Create new empty lists from items within a Python list?

my_list = ['c1','c2','c3']

Is there anyway to create a certain amount of new lists based on items inside of a list? 无论如何,基于列表中的项目创建一定数量的新列表?

Result would be: 结果将是:

c1 = []
c2 = []
c3 = []

You can do that using globals() : 您可以使用globals()做到这一点:

>>> my_list = ['c1','c2','c3']
>>> for x in my_list:
...     globals()[x] = []
...     
>>> c1
[]
>>> c2
[]
>>> c3
[]

But it's better to use a dict here: 但是最好在这里使用字典:

>>> dic = {item : []  for item in my_list}
>>> dic
{'c2': [], 'c3': [], 'c1': []}

Instead of creating new global variables using the names from your list, I would suggest using a dictionary: 建议不要使用列表中的名称来创建新的全局变量,而建议使用字典:

my_list = ['c1', 'c2', 'c3']
my_dict = {k: [] for k in my_list}

Then to access one of those lists you could use something like my_dict['c1'] or my_dict['c2'] . 然后,要访问这些列表之一,可以使用诸如my_dict['c1']my_dict['c2']

Another solution would be to add the new lists as attributes to some object or module. 另一个解决方案是将新列表作为属性添加到某个对象或模块。 For example: 例如:

lists = type('Lists', (object,), {k: [] for k in my_list})

After which you could access your lists using lists.c1 , lists.c2 , etc. 之后,您可以使用lists.c1lists.c2等访问列表。

In my opinion both of these methods are cleaner than modifying globals() or locals() and they give you very similar behavior. 在我看来,这两种方法都比修改globals()locals()更干净,并且它们为您提供了非常相似的行为。

Note that if you are on Python 2.6 or below you will need to replace the dictionary comprehensions with dict((k, []) for k in my_list) . 请注意,如果您使用的是Python 2.6或更低版本,则需要用dict((k, []) for k in my_list)替换字典dict((k, []) for k in my_list)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM