简体   繁体   English

Python:我们可以从字典或类似ts的对象中获取值吗?

[英]Python: can we get the value from the dict or object like the ts?

Isn't the python can get the object or dict like ts: python不能像ts那样获得对象或字典:

 let test = {a: 1, b: 2, c:3} const {a, b} = test 
The a and b are the key and the variable, it looks simple and not need two line code or for...in to get the a and b . ab是键和变量,它看起来很简单,不需要两行代码或for...in即可获得ab

The closest you'll get is something along the lines of: 您将获得的最接近的东西类似于:

a, b = test['a'], test['b']  # dicts
a, b = test.a, test.b        # objects

Or, less repetitive if you have more: 或者,如果您有更多,请减少重复性:

a, b, c = (test[i] for i in ('a', 'b', 'c'))           # dicts
a, b, c = (getattr(test, i) for i in ('a', 'b', 'c'))  # objects

You could probably do funky things with using the locals() or globals() dicts and .update ing them with a set intersection for example, but you should always explicitly declare variables and not muck around with scope dicts. 你也许可以做到时髦的东西用的locals()globals()类型的字典和.update与例如交集荷兰国际集团他们,但你应该始终明确声明变量,而不是与范围类型的字典弄脏周围。

You can do something like this. 你可以做这样的事情。

>>>
>>> d = {"a": 1, "b": 2, "c": 3}
>>>
>>> a, b, c = (lambda a, b, c: (a, b, c))(**d)
>>> a
1
>>> b
2
>>> c
3
>>>

Here is another example where we will only get few values. 这是另一个例子,我们只会得到很少的值。

>>> d2 = {"a": 1, "b": 2, "c": 3, "d": 4}
>>> a, b = (lambda a, b, **kwargs: (a, b))(**d2)
>>> a
1
>>> b
2
>>>

Just use two lines. 只需使用两行。 Anything else which works in one line is too clever, too hard to understand, and too easy to break in the future: 一行中的其他任何事情都太聪明,太难理解了,将来也很容易突破:

test = {'a': 1, 'b': 2, 'c':3}
a = test['a']
b = test['b']

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

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