Python的list type有一个index()方法,该方法接受一个参数并返回列表中与该参数匹配的第一个项的索引。例如:
>>> some_list = ["apple", "pear", "banana", "grape"]
>>> some_list.index("pear")
1
>>> some_list.index("grape")
3
有没有一种优雅的(惯用的)方法可以将它扩展到复杂对象的列表中,比如元组?理想情况下,我希望能够这样做:
>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> some_list.getIndexOfTuple(1, 7)
1
>>> some_list.getIndexOfTuple(0, "kumquat")
2
getIndexOfTuple()只是一个假设方法,它接受一个子索引和一个值,然后返回列表项的索引以及该子索引处的给定值。我希望
有没有什么方法可以达到一般的结果,使用列表理解或lambas或类似的“内联”的东西?我想我可以编写自己的类和方法,但是如果Python已经有办法的话,我不想重新发明轮子。
过了一段时间,那些单子的理解很混乱。
我喜欢这种Python式的方法:
如果你需要你的代码是所有超级性能:
这个怎么样?
正如评论中指出的,这将得到所有匹配。为了得到第一个,你可以:
在评论中有一个很好的讨论,关于发布的所有解决方案之间的速度差。我可能有点偏颇,但我个人会坚持使用一行代码,因为我们讨论的速度与为这个问题创建函数和导入模块相比是微不足道的,但是如果您计划对大量元素执行此操作,您可能需要查看提供的其他答案,因为它们比我提供的要快提供。
一种可能是使用
operator
模块中的itemgetter函数:对
itemgetter
的调用返回一个函数,该函数将对传递给它的任何内容执行与foo[0]
等价的操作。使用map
,然后将该函数应用于每个元组,将信息提取到新列表中,然后在该列表上正常调用index
。相当于:
这又相当于:
它给出:
相关问题 更多 >
编程相关推荐