0
results = [({'age': 1},      30), 
           ({'weight': 80},   5), 
           ({'label': 'abc'}, 7)]

As shown above, I have a list of tuples. Is there any elegant way to get the tuple whose has the smallest 2nd item?

More generally, if I need to get the tuple who has the smallest eval(2nd item)? eval is a transformation function.

iz_
  • 15,923
  • 3
  • 25
  • 40
Indominus
  • 1,228
  • 15
  • 31

1 Answers1

1

You can use the key arg of min with operator.itemgetter:

from operator import itemgetter

results = [({'age': 1},      30), 
           ({'weight': 80},   5), 
           ({'label': 'abc'}, 7)]

print(min(results, key=itemgetter(1)))

Output:

({'weight': 80}, 5)
iz_
  • 15,923
  • 3
  • 25
  • 40
  • beautiful, as my second question, i guess it is just something like `min(results, key=lambda t: t[1]**2)` – Indominus Jan 24 '19 at 02:37
  • 1
    You could also use a `lambda` function instead of `itemgetter` and avoid an import by replacing `itemgetter(1)` with `lambda x: x[1]` – Jebby Jan 24 '19 at 02:37
  • thanks Jebby, I was just commenting the same:) – Indominus Jan 24 '19 at 02:38
  • @Jebby Yeah, but it's less efficient. `itemgetter` is a little faster. – iz_ Jan 24 '19 at 02:38
  • @Indominus Yeah, you can do `min(results, key=lambda t: yourfunc(t[1]))`. You define `yourfunc`. – iz_ Jan 24 '19 at 02:39
  • @Tomothy32 The `timeit` module says that `lambda` without the import is .05 seconds faster on average with 10000 tests. Just running `timeit` on the import is consistently .03 seconds for me. – Jebby Jan 24 '19 at 02:46
  • @Jebby You must've included the import with your timing. See https://stackoverflow.com/a/41787974 and https://stackoverflow.com/q/17243620 – iz_ Jan 24 '19 at 02:48
  • @Tomothy32 Yes. You need the import for itemgetter, not for lambda. – Jebby Jan 24 '19 at 02:49
  • @Jebby Yes, but the `import` is a one-time thing. If you are using `itemgetter` multiple times, for example in a `for` loop, it's worth it. – iz_ Jan 24 '19 at 02:51
  • @Tomoth32 After another `timeit` test by only importing the module once, `itemgetter` was only faster than `lambda` once on average over 10000 runs consistently. Sorry if I'm sounding pedantic, this just intriuged me. – Jebby Jan 24 '19 at 03:06
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/187220/discussion-between-tomothy32-and-jebby). – iz_ Jan 24 '19 at 03:07