简体   繁体   English

如何在python中创建一个包含对象的列表

[英]How to create a list with objects in python

list_name = "a"
list_element = "b"

I want to create a list in below format我想创建以下格式的列表

a = ["b"]

How cani achieve this with format of list_name and list_element ?如何使用list_namelist_element格式实现此list_element

Thank you!谢谢!

You can do this easily using globals() :您可以使用globals()轻松完成此操作:

globals()[list_name] = [list_element]

out put:输出:

In [1]: list_name = "a" 
In [2]: list_element = "b" 

In [3]: globals()[list_name] = [list_element]                                                                                                                                                                      

In [4]: a                                                                                                                                                                                                          
Out[4]: ['b']

Read more about globals() .阅读更多关于globals() 的信息

What you are trying to do here is to create variable names dynamically.您在这里尝试做的是动态创建变量名称。 Except if you really really need to do it, it is not recommended and can usually be avoided.除非你真的真的需要这样做,否则不推荐这样做,通常可以避免。

In Python, dictionaries can be used to solve this problem.在 Python 中,可以使用字典来解决这个问题。 A dictionary contains variables which can be called using "keys".字典包含可以使用“键”调用的变量。

dict = {'a1' : "b1",
        'a2' : "b2"}

The variable (here the string "b1") associated with the key 'a1' can be called using:可以使用以下方法调用与键 'a1' 关联的变量(此处为字符串“b1”):

dict['a1']

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

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