IwillGetThere
IwillGetThere

Reputation: 11

Getting smallest number in array python

I am trying to program in python

I have an array which holds data like

[A,20,False] [B,1,False] [C, 8, False]

I want to be able to loop through the array by getting the element with the lowest middle number so e.g. the next element to be worked on would be B because it has the smallest number one. Then this gets deleted so then the next element to be used would be C because out of 20 and 8 8 is the smallest number...

hope ive made this clear

Please help

Thank you

Upvotes: 1

Views: 3173

Answers (3)

rmalouf
rmalouf

Reputation: 3443

This will give you the item with the smallest number:

from operator import itemgetter

next = min(array,key=itemgetter(1))[0]

You can also sort the list using the second item as the key:

array.sort(array,key=itemgetter(1))

Upvotes: 2

orlp
orlp

Reputation: 117641

First sort the list and then loop through it as you said:

somelist = [[A,20,False] [B,1,False] [C, 8, False]]
somelist.sort(lambda x, y: cmp(x[1], y[1]))

for smallest in somelist:
    # do stuff with the smallest member

Upvotes: 0

Daniel DiPaolo
Daniel DiPaolo

Reputation: 56390

>>> myList = [["A", 20, False], ["B", 1, False], ["C", 8, False]]
>>> smallest = min(myList, key=lambda L: L[1])
>>> smallest
['B', 1, False]

If you'd like to sort it using that element you can do the same thing with sorted:

>>> sorted(myList, key=lambda L: L[1])
[['B', 1, False], ['C', 8, False], ['A', 20, False]]

Upvotes: 5

Related Questions