如何以最有效的方式计算嵌套字典中的子元素数?len()函数不能像我最初期望的那样工作:
>>> food_colors = {'fruit': {'orange': 'orange', 'apple': 'red', 'banana': 'yellow'}, 'vegetables': {'lettuce': 'green', 'beet': 'red', 'pumpkin': 'orange'}}
>>> len(food_colors)
2
>>>
Run Code Online (Sandbox Code Playgroud)
如果我真的想要计算子元素的数量怎么办?(例如,预期结果为"6")是否有更好的方法来执行此操作而不是循环遍历每个元素并总结子元素的数量?在这个特定的应用程序中,我有大约500万个子元素需要计数,每个时钟周期都很重要.
zwo*_*wol 17
是否保证每个顶级键都有一个字典作为其值,并且没有二级键具有字典?如果是这样,这将是您希望的最快速度:
sum(len(v) for v in food_colors.itervalues())
Run Code Online (Sandbox Code Playgroud)
如果数据结构更复杂,当然需要更多代码.我不知道有任何内在函数来进行深度数据结构遍历.
任意深度,一个班轮:
def count(d):
return sum([count(v) if isinstance(v, dict) else 1 for v in d.values()])
Run Code Online (Sandbox Code Playgroud)
对于您的具体问题,您可以使用此:
>>> d={'fruit':
{'orange': 'orange', 'apple': 'red', 'banana': 'yellow'},
'vegetables':
{'lettuce': 'green', 'beet': 'red', 'pumpkin': 'orange'}}
>>> len(d)
2 # that is 1 reference for 'fruit' and 1 for 'vegetables'
>>> len(d['fruit'])
3 # 3 fruits listed...
>>> len(d['vegetables'])
3 # you thought of three of those...
>>> len(d['fruit'])+len(d['vegetables'])
6
Run Code Online (Sandbox Code Playgroud)
虽然您可以使用Python所具有的各种工具来计算这个简单字典中的元素,但是首先考虑数据结构的更有趣和更有成效.
Python的基本数据结构是列表,集合,元组和字典.这些数据结构中的任何一个都可以通过引用"保存"其自身或其他数据结构的任何嵌套版本.
此列表是嵌套列表:
>>> l = [1, [2, 3, [4]], [5, 6]]
>>> len(l)
3
>>> l[0]
1
>>> l[1]
[2, 3, [4]]
>>> l[2]
[5, 6]
Run Code Online (Sandbox Code Playgroud)
第一个元素是整数1.元素1和2是列表本身.任何其他基本Python数据结构都是如此.这些是递归数据结构.你可以用pprint打印它们
如果您更好地组织字典,使用Python最简单的工具从中提取信息会更容易:
>>> color='color'
>>> family='family'
>>> sensation='sensation'
>>> good_things={
'fruit':
{
'orange':
{
color: 'orange',
family: 'citrus',
sensation: 'juicy'
},
'apple':
{
color: ['red','green','yellow'],
family:'Rosaceae',
'sensation': 'woody'
},
'banana':
{
color: ['yellow', 'green'],
family: 'musa',
sensation: 'sweet'
}
},
'vegatables':
{
'beets':
{
color: ['red', 'yellow'],
family: 'Chenopodiaceae',
sensation: 'sweet'
},
'broccoli':
{
color: 'green',
family: 'kale',
sensation: 'The butter you put on it',
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在针对该数据的查询更有意义:
>>> len(good_things)
2 # 2 groups: fruits and vegetables
>>> len(good_things['fruit'])
3 # three fruits cataloged
>>> len(good_things['vegetables'])
2 # I can only think of two vegetables...
>>> print good_things['fruit']['apple']
{'color': ['red', 'green', 'yellow'], 'sensation': 'woody', 'family': 'Rosaceae'}
>>> len(good_things['fruit']['apple']['color'])
3 # apples have 3 colors
Run Code Online (Sandbox Code Playgroud)
您可以使用递归函数执行此操作。
>>> x
{'a': 1, 'b': 2, 'c': 3, 'd': {'I': 1, 'II': 2, 'III': 3}, 'e': 5}
>>> def test(d):
... cnt = 0
... for e in d:
... if type(d[e]) is dict:
... cnt += test(d[e])
... else:
... cnt += 1
... return cnt
...
>>> test(x)
7
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20960 次 |
| 最近记录: |