如何从元组字典中对 min/max 进行排序?

How to sort for min/max from a dictionary of tuples?

src_type 是元组字典,数据结构为 (start,end,frequency)

In [303]: src_type
Out[303]: 
{'A': (440468754.0, 442213325.0, 25),
'B': (440448179.523912, 442202204.43813604, 285),
'C': (440447107.044571, 442268070.552849, 4914),
'D': (440448307.44081604, 442254145.172575, 443),
'E': (440458084.535652, 442253729.048885, 3060)}

我想找到 "start" 的最小值和 "end"

的最大值

这些是我的解决方案:

1(简单又蹩脚)

end_ts = 0
for i in src_type.values():
    if end_ts < i[1]:
        end_ts = i[1]
start_ts = end_ts

for i in src_type.values():
    if start_ts > i[0]:
        start_ts = i[0]

2(在 SO 的帮助下排序 {})

b = src_type.items()
b.sort(key=lambda x:x[1][0])
min_start = b[0][1][0]
b.sort(key=lambda x:x[1][1])
max_end = b[-1][1][1]

他们是更好的优雅解决方案吗?

也许:

b = src_type.values()
min_start = min(x[0] for x in b)
max_end = max(x[1] for x in b)

可以做得更短,但效率更低:

min_start = min(x[0] for x in src_type.values())
max_end = max(x[1] for x in src_type.values())

我会使用 min()max() 以及 generator expressions:

In [6]: min(start for (start, end, frequency) in src_type.values())
Out[6]: 440447107.044571

In [7]: max(end for (start, end, frequency) in src_type.values())
Out[7]: 442268070.552849

如果你愿意,你可以分解 src_type.values()

我选择使用 startendfrequency 的符号名称,在我看来这提高了代码的清晰度。

看起来这可能有效:

start = min([item[0] for item in src_type.values()])
end = max([item[1] for item in src_type.values()])