python等效于朱莉娅unfack.jl

发布于 2025-02-06 12:29:18 字数 879 浏览 0 评论 0原文

朱莉娅(Julia)有一个称为 uncack.jl 可以将dict dict或nater命名为变量转换为变量的软件包。例如,给定dict

params = Dict(:a=>5.0, :b=>2, :c=>"Hi!")

值与键相同的变量解封,从而获得a a c :

@unpack a, c = params

i可以通过将dict中的 是:

  • ac以这种方式创建的c 不会通过薄荷工具将其视为“未定义变量”;
  • 要解开包装的变量的顺序可以是任意的。唯一的要求是,变量名与字典中的键相同。
  • 在这里,我不想使用b,因此@unpack不会创建b。换句话说,我完全控制要提取哪些变量。不需要的变量将不会创建。

在Python中有类似的(甚至是同等)软件包可以解开dict?特别是,请避免locals()evalexec,因为伸长工具无法识别变量的定义,或者它们是< a href =“ https://stackoverflow.com/questions/1933451/why-should-should-should-exec-and-eval-be-be-avo-”>“危险”功能不建议使用。

Julia has a package called UnPack.jl that can convert Dict or NamedTuple to variables. For example, given the Dict

params = Dict(:a=>5.0, :b=>2, :c=>"Hi!")

I can get a and c by unpacking the values in the Dict to variables with the same name as the keys:

@unpack a, c = params

Some great features of UnPack.jl are:

  • a, c created in this way will not be treated as "undefined variables" by linting tools;
  • The order of the variables to be unpacked can be arbitrary; the only requirement is that the variable names are the same as the keys in the dictionary.
  • Here I do not want to use b, so @unpack will not create b. In other words, I have full control on what variables are to be extracted; unneeded variables will not be created.

It there a similar (or even equivalent) package in Python to unpack a dict? In particular, please avoid locals(), eval, exec because either the linting tools cannot recognize the definition of the variables, or they are "dangerous" functions not recommended for use.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

电影里的梦 2025-02-13 12:29:18

它在全球名称空间中放置了新变量:(,但是:

d = {'a' : 5.0, 'b' : 2, 'c' : "Hi!"}
globals().update((k, d[k]) for k in ['a', 'b', 'c'])

It puts new variables in global namespace :(, but:

d = {'a' : 5.0, 'b' : 2, 'c' : "Hi!"}
globals().update((k, d[k]) for k in ['a', 'b', 'c'])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文