3

I have the following list of tuples

lstoflsts = [(1.2, 2.1, 3.1), (0.9, 3.4, 7.4), (2.3, 1.1, 5.1)] 

I would like to get the minimum value of the 2nd column (which is 1.1 based on above example).

I tried playing around with min(listoflists) without success.

any suggestions how to approach?
note: if possible I would like to avoid looping over rows and columns...

3
  • 5
    min(zip(*lstoflsts)[1])? Commented Aug 25, 2015 at 13:33
  • @muddyfish: very elegant. please add it as an answer. Commented Aug 25, 2015 at 13:41
  • 1
    More precisely, you have a list of tuples. If you use a numpy array instead, you can just do min(lstoflsts[:,1]). Commented Aug 25, 2015 at 13:42

5 Answers 5

11

Simplest way, you can use min,

>>> lstoflsts = [(1.2, 2.1, 3.1), ... (0.9, 3.4, 7.4), ... (2.3, 1.1, 5.1)] >>> >>> min(lstoflsts, key=lambda x: x[1]) (2.3, 1.1, 5.1) >>> min(lstoflsts, key=lambda x: x[1])[1] 1.1 
Sign up to request clarification or add additional context in comments.

Comments

5

As requested by @udo,

min(zip(*lstoflsts)[1]) 

This will change the list so the columns are rows (rotate it) and then get the 2nd (0 based indexing) row (previously column).

Finally, it returns the minimun value.

1 Comment

and in python 3 it would be min(list(zip(*lstoflsts))[1])
4

Just for the love of generator expressions:

min(x[1] for x in lstoflsts) 

Comments

1

While sharing a love of generator expressions (which in this case is both one line and beautifully self-documenting once you know Python), is there anything actually wrong with

m =lstoflsts[0][1] for x in lstoflsts: m = min(m, x[1] ) 

Comments

1

It works exactly the same way you'd sort a list according to that criterion. Pass a key function:

min(iterable[, key]):

[...] The optional key argument specifies a one-argument ordering function like that used for list.sort().

For example using operator.itemgetter():

import operator lstoflsts = [(1.2, 2.1, 3.1), (0.9, 3.4, 7.4), (2.3, 1.1, 5.1)] print min(lstoflsts, key=operator.itemgetter(1)) # prints (2.3, 1.1, 5.1) 

You can also use a lambda expression as key function, of course. However, using operator.itemgetter() is generally considered more efficient than the lambda function. It is especially more efficient than anything involving zip().

For reference:

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.