简体   繁体   中英

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

src_type is a dictionary of tuples with the data structured as (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)}

I would like to find the min of "start" and the max of "end"

These are my solutions:

1 (simple and crappy)

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 (with some help from SO about sorting {})

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]

Is their a better an elegant solution ?

Maybe:

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

Which could be made even shorter, but less efficient:

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

I would use min() and max() with 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

You could factor out src_type.values() if you like.

I chose to use symbolic names for start , end and frequency as to my eyes this improves the clarity of the code.

Looks like this might work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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