简体   繁体   中英

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 eg 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

>>> 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]]

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))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM