在元组或对象列表上使用Python的list index()方法? [英] Using Python's list index() method on a list of tuples or objects?

查看:115
本文介绍了在元组或对象列表上使用Python的list index()方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python的列表类型具有index()方法,该方法采用一个参数并返回列表中与该参数匹配的第一项的索引.例如:

Python's list type has an index() method that takes one parameter and returns the index of the first item in the list matching the parameter. For instance:

>>> some_list = ["apple", "pear", "banana", "grape"]
>>> some_list.index("pear")
1
>>> some_list.index("grape")
3

是否有一种优美的(惯用的)方式将其扩展到诸如元组之类的复杂对象列表?理想情况下,我希望能够执行以下操作:

Is there a graceful (idiomatic) way to extend this to lists of complex objects, like tuples? Ideally, I'd like to be able to do something like this:

>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> some_list.getIndexOfTuple(1, 7)
1
>>> some_list.getIndexOfTuple(0, "kumquat")
2

getIndexOfTuple()只是一个假设的方法,该方法接受一个子索引和一个值,然后返回在该子索引处具有给定值的列表项的索引.我希望

getIndexOfTuple() is just a hypothetical method that accepts a sub-index and a value, and then returns the index of the list item with the given value at that sub-index. I hope

是否有某种方法可以使用列表推导或lambas或类似的内联"方法来达到该总体结果?我想我可以编写自己的类和方法,但是如果Python已经有办法做的话,我不想重新发明轮子.

Is there some way to achieve that general result, using list comprehensions or lambas or something "in-line" like that? I think I could write my own class and method, but I don't want to reinvent the wheel if Python already has a way to do it.

推荐答案

如何?

>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> [x for x, y in enumerate(tuple_list) if y[1] == 7]
[1]
>>> [x for x, y in enumerate(tuple_list) if y[0] == 'kumquat']
[2]

正如评论中指出的那样,这将获得所有匹配项.要获得第一个,您可以执行以下操作:

As pointed out in the comments, this would get all matches. To just get the first one, you can do:

>>> [y[0] for y in tuple_list].index('kumquat')
2

评论中对所有发布的解决方案之间的速度差异进行了很好的讨论.我可能有一点偏见,但我个人会坚持一言以蔽之,因为相对于创建函数和导入模块来解决这个问题,我们谈论的速度是微不足道的,但是如果您打算大量这样做您可能希望查看提供的其他答案,因为它们比我提供的要快.

There is a good discussion in the comments as to the speed difference between all the solutions posted. I may be a little biased but I would personally stick to a one-liner as the speed we're talking about is pretty insignificant versus creating functions and importing modules for this problem, but if you are planning on doing this to a very large amount of elements you might want to look at the other answers provided, as they are faster than what I provided.

这篇关于在元组或对象列表上使用Python的list index()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆