本文介绍了python的递归itemgetter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
python 中是否有递归的 itemgetter
.假设你有一个像
Is there a recursive itemgetter
in python. Let's say you have an object like
d = {'a': (1,2,3), 'b': {1: (5,6)}}
我想从 d['a']
获取元组的第一个元素?据我所知 itemgetter
只会做一个级别,即获取我 a
或 b
或两者.
and I wanted to get the first element of the tuple from d['a']
? As far as I can tell itemgetter
will only do one level, i.e. get me a
or b
or both.
是否有一些巧妙的方法将 itertools
与 itemgetter
结合以产生所需的结果.
Is there some clever way of combining itertools
with itemgetter
to produce the desired result.
所以基本上我想要能够调用的是
So basically what I want to be able to call is
from operator import itemgetter
d = {'a': (1,2), 'b': (4, (5,))}
itemgetter({'a': 0})(d) --> 1
itemgetter({'b': 0})(d) --> 4
itemgetter({'b': {1: 0}})(d) --> 5
d = {'a': {'b': (1,2,3)}}
itemgetter({'a': {'b': 2}})(d) --> 3
推荐答案
我不喜欢聪明"的方式.明显更好.
I don't like 'clever' ways. Obvious is better.
您可以非常轻松地编写一个沿下标列表迭代的 getter:
You can very easily write a getter that iterates along a list of subscripts:
def getter(x, *args):
for k in args:
x = x[k]
return x
>>> d = {'a': (1,2,3), 'b': {1: (5,6)}}
>>> getter(d, 'a', 0)
1
这篇关于python的递归itemgetter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!