Using Python#39;s list index() method on a list of tuples or objects?(在元组或对象列表上使用 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() 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在元组或对象列表上使用 Python 的 list index() 方法?
基础教程推荐
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 筛选NumPy数组 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01