1

I wonder if it is possible to achieve the following in Python:

I have a nested dictionary nested_dict, which maps each three-element tuple (a, b, c) to a sub-dictionary sub_dict, and I have another list list_b containing all the elements corresponding to the second element (i.e. the one denoted by b) in the tuple keys above.

Given nested_dict and list_b, as well as a fixed pair of a and c (i.e. the first and the third element of a tuple key, respectively), I want to obtain a sorted iterator over the sub-dictionaries based on the elements in list_b that forms a part of the tuple keys, in other words, by using this iterator, I can iterate through the returned sub-dictionaries like this:

nested_dict[(a, b_1, c)], nested_dict[(a, b_2, c)], nested_dict[(a, b_3, c)], ...

where, b_1 < b_2 < b_3 ... and each b_i is in list_b

I am thinking along this line:

def sorted_dict_itr (nested_dict, list_b, a, c):
    return (nested_dict[(a, b, c)] for b in sorted(list_b))

But would this always return an iterator over nested_dict[(a, b, c)] by the order of b? If so, is there any more efficient way (meaning speedier code) to achieve the same?

4

2 回答 2

1

是的,它应该,假设您想要默认强加的b元素的顺序。sorted()

于 2012-06-05T18:49:52.980 回答
1

是的,它有效。

保留一个排序的集合代替保留 list_b 并动态排序将提高效率——但当然它可能会降低其他更重要的地方的效率。

没有其他方法可以提高算法的复杂性——dict 查找是恒定时间的,迭代列表的速度与迭代任何可能的速度一样快。

通过避免需要以各种不同的方式散列每个 (a, b, c) 元组,您可能可以通过一个小的常数因子来加快速度,但我怀疑这会产生很大的不同。

您可以通过与变量范围相关的各种微优化以及是否产生值或返回生成器来通过一些操作码来加快速度,但很难想象这会很重要。

于 2012-06-05T21:53:17.547 回答