简体   繁体   中英

Find index in SortedCollection

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>

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

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