I have a set called ISET; with a long list of 3-letter elements like: USA, BRA, CHN, ....
I also have a dictionary called heights. The keys for this dictionary are the elements of SET combined with a certain YEAR string. For example: USA1991, USA1992, ..., BRA1991, ... ...
What is the best way of finding the max height-value across all countries for a given year?
开发者_如何学CThis is what I have been using:
YEAR = getuserselection()
for i in ISET:
z = heights.get(i + YEAR, None)
if z is None: continue
if z > Max: Max = z
Any suggestions for improving it?
Thank you.
Suggestion, not actually measured: use a mapping heights_per_year
from years to dict
s mapping country codes to heights.
year = getuserselection()
heights = heights_per_year[int(year)]
max_height = max(a.itervalues())
Note the conversion to int
for some extra speed (no need to compare strings).
Better yet, let height_per_year
map to descending sorted list
s of (country code, height) pairs.
max_height = heights[0][1]
If height
doesn't change much, cache the statistics you need, when you create or update the data.
What is just a rewording of your algorithm could be:
YRNormalizer = max(heights.get(z+YEAR, -99999) for z in ISET)
If you can you should have python doing the loops itself...
精彩评论