gpt4 book ai didi

javascript - JS风格的字典初始化快捷方式?

转载 作者:行者123 更新时间:2023-11-30 20:15:03 26 4
gpt4 key购买 nike

在 JavaScript 中,您可以像这样初始化一个对象:

{ a, b }

其中 ab 是声明的变量。初始化将在新对象中使用它们的值。

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))

关于javascript - JS风格的字典初始化快捷方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52007266/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com