开发者

Getting smallest number in array python

I am trying to program in python

I have an array which hold开发者_JS百科s 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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜