python - 创建一个名称与列表中项目名称相同的变量

标签 python python-3.x

<分区>

出于好奇只是一个愚蠢的问题。

假设有一个包含元素的列表

fruits_lst = ['apples','oranges','bananas','guavas']

现在是否可以创建单独的单独字典,但名称作为列表中元素的名称?

期望的结果:

apples=dict()
oranges=dict()
bananas=dict()
guavas=dict()

我知道可以通过查看元素的名称轻松做到这一点,但我想要实现的是程序以某种方式在遍历元素名称时获取元素名称,然后创建具有相同名称的空字典。是否可以?请指导我完成..

最佳答案

使用dict代替globals

不推荐使用全局变量。字典的字典更加简洁和易于维护。例如,使用 dictionary comprehension :

fruits_lst = ['apples', 'oranges', 'bananas', 'guavas']

d = {fruit: {} for fruit in fruits_lst}

然后通过d['apples']d['oranges']等访问特定的内部字典

参见 this answer解释为什么这是有用的,here再举个例子。

关于python - 创建一个名称与列表中项目名称相同的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53865371/

相关文章:

python - 如何使 spaCy 匹配不区分大小写

python - 类型错误 : function missing 1 required positional argument

python - 如何查找文件中特定索引处的列表值(例如 : [1, 2,3])的所有实例

python-3.x - 一步步: Installing Python 3. 3、Ubuntu 12.04上的Lighttpd & Pymongo

python - 用 Python 实现了广度优先搜索算法。不知道如何返回解决方案

Python 基于输入的动态模块加载

python-3.x - python3的编码问题并单击包

python-3.x - 如何在本地对 python 3 应用程序引擎应用程序进行单元测试?

python - 将列表列表作为输入传递给 scipy.optimize.curve_fit

python - 确定集合并集的有效方法