Created
April 13, 2017 04:44
-
-
Save lihuanshuai/8c683e2bed4905c5d3f1f37eea16fa12 to your computer and use it in GitHub Desktop.
对于每个 key,仅选取最小(或最大)值作为 value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def gen_reduced_dict(iterable, key=None, reverse=False): | |
key = (lambda x: x) if key is None else key | |
d = {} | |
for k, v in iterable: | |
if k not in d: | |
d[k] = v | |
pv = d[k] | |
cmp_ = (lambda x, y: x > y) if reverse else (lambda x, y: x < y) | |
if cmp_(key(v), key(pv)): | |
d[k] = v | |
return d |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment