0

I use this implementation of SortedCollection.

>>> a = SortedCollection(key=itemgetter(1))
>>> a.insert_right(('A',5))
>>> a.insert_right(('B',3))
>>> a.insert_right(('C',7))
>>> a
SortedCollection([('B', 3), ('A', 5), ('C', 7)], key=<operator.itemgetter object at 0x028C99B0>)

What would be the syntax of finding the index of the item with 'A'?
Notice that 'A' is not the sorting key I chose.

Here's a failed way to do it:

>>> a.find(lambda item: item[0]=='a')

Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    a.find(k=lambda item: item[0]=='a')
  File "C:/dev/sorted_collection.py", line 167, in find
    raise ValueError('No item found with key equal to: %r' % (k,))
ValueError: No item found with key equal to: <function <lambda> at 0x028DB270>
Jonathan Livni
  • 101,334
  • 104
  • 266
  • 359
  • 1
    Does this address your problem? http://stackoverflow.com/questions/946860/using-pythons-list-index-method-on-a-list-of-tuples-or-objects/946906#946906 – Acorn Oct 30 '11 at 13:37
  • If you need to look up items by the first item, then you should use a structure where that is the key, rather than the second item. – agf Oct 30 '11 at 13:40
  • @agf - That was my initial thought as well, however the main function of the structure is keeping the items sorted, a collection that would include two keys - one for access and one for sorting would suite me best, alas I didn't find one and it's not worth implementing one at this point – Jonathan Livni Oct 30 '11 at 20:20

2 Answers2

1

Tested:

[x[0] for x in a].index('A')

SortedCollection behaves much like a list, so it's actually the same syntax as searching in

[('B', 3), ('A', 5), ('C', 7)]
Jonathan Livni
  • 101,334
  • 104
  • 266
  • 359
1
a = SortedCollection(key=itemgetter(1))
a.insert_right(('A',5))
a.insert_right(('B',3))
a.insert_right(('C',7))

print [y[0] for y in a].index('B')

Result:

0
Acorn
  • 49,061
  • 27
  • 133
  • 172