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

查看:12
本文介绍了在元组或对象列表上使用 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天全站免登陆