简体   繁体   English

在SortedCollection中查找索引

[英]Find index in SortedCollection

I use this implementation of SortedCollection . 我使用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' ? 使用'A'查找项目索引的语法是什么?
Notice that 'A' is not the sorting key I chose. 请注意, 'A'不是我选择的排序键。

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 SortedCollection行为很像列表,所以它实际上与搜索的语法相同

[('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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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