javascript - JS风格的字典初始化快捷方式?
问题描述
在 JavaScript 中,你可以像这样初始化一个对象:
{ a, b }
wherea
和b
是声明的变量。初始化将在新对象中使用它们的值。
Python中有类似的东西吗?
解决方案
您可以实现自己的解释器来满足这样的要求:
import re
# Set up local variable enviroment
#
# without the following assignment expressions,
# my lambda expression will return an empty dict
a = 1
b = 2
print((lambda str: (lambda f, z: { **f(globals(), z), **f(locals(), z) })(lambda s, t: { k: v for k, v in s.items() if t(k) },(lambda l: lambda k: k[0] is not '_' and k[-1] is not '_' and k in l)(re.sub(r'[\s\{\}]+', '', str).split(','))))('{ a, b }'))
输出将是:
{'a': 1, 'b': 2}
但是convert
,只能消化简单的用例,例如您的,没有嵌套结构。
更人性化的版本:
import re
example_string = '{ a, b }'
def convert_string_to_dict(example_string):
list_of_variables = re.sub(r'[\s\{\}]+', '', example_string).split(',')
def validate(key):
return key[0] is not '_' \
and key[-1] is not '_' \
and key in list_of_variables
def make_dict_from_environment(env):
return { key: val for key, val in env.items() if validate(key) }
merge_two_dicts = { **make_dict_from_environment(globals()), **make_dict_from_environment(locals()) }
return merge_two_dicts
# Set up local variable enviroment
#
# without the following assignment expressions,
# `convert_string_to_dict('{ a, b }')` will return an empty dict
a = 1
b = 2
print(convert_string_to_dict(example_string))
推荐阅读
- java - 无法提交 JPA 事务:嵌套异常是 javax.persistence.RollbackException:提交事务时出错
- r - 使用 Ggplot2 汇总均值的分组条形图
- java - 在玩家改变世界时,给物品一个 delai - Minecraft - java
- google-cloud-run - 端点开发者门户“试用此 API”和权限
- python - 如何比较熊猫,python中的列行
- javascript - next.config.json 中的多重导出
- reactjs - TabPanel:警告:validateDOMNesting(...):不能作为后代出现
- python - Matlab 的 pathtool 添加的 Python 等价物是什么?
- node.js - 树莓派节点服务器没有连接到其他机器
- checkstyle - 是否有强制类中的每个字段都有注释的检查样式规则?