Skip to content

Instantly share code, notes, and snippets.

@lihuanshuai
Created April 13, 2017 04:44
Show Gist options
  • Save lihuanshuai/8c683e2bed4905c5d3f1f37eea16fa12 to your computer and use it in GitHub Desktop.
Save lihuanshuai/8c683e2bed4905c5d3f1f37eea16fa12 to your computer and use it in GitHub Desktop.
对于每个 key,仅选取最小(或最大)值作为 value
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