1

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

2
  • This isn't very clear.. Is this a multidimensional array, i.e. [[A][20][False]][[B][1][False]][[C][8][False]], or is the content a string like "A,20,False"? Commented Mar 14, 2011 at 22:27
  • sorry a multidimensional array Commented Mar 14, 2011 at 22:28

3 Answers 3

5
>>> 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]]
Sign up to request clarification or add additional context in comments.

2 Comments

i get the following error:AttributeError: Node instance has no attribute 'getitem'
Can you post the code that got you that error? The stuff I pasted above was run as-is in the Python interpreter and you can see the results.
2

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.