在元组或对象列表上使用Python的list index()方法?

2024-09-24 02:26:07 发布

您现在位置:Python中文网/ 问答频道 /正文

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已经有办法的话,我不想重新发明轮子。


Tags: 对象方法apple列表参数indextypesome
3条回答

过了一段时间,那些单子的理解很混乱。

我喜欢这种Python式的方法:

from operator import itemgetter

def collect(l, index):
   return map(itemgetter(index), l)

# And now you can write this:
collect(tuple_list,0).index("cherry")   # = 1
collect(tuple_list,1).index("3")        # = 2

如果你需要你的代码是所有超级性能:

# Stops iterating through the list as soon as it finds the value
def getIndexOfTuple(l, index, value):
    for pos,t in enumerate(l):
        if t[index] == value:
            return pos

    # Matches behavior of list.index
    raise ValueError("list.index(x): x not in list")

getIndexOfTuple(tuple_list, 0, "cherry")   # = 1

这个怎么样?

>>> 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]

正如评论中指出的,这将得到所有匹配。为了得到第一个,你可以:

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

在评论中有一个很好的讨论,关于发布的所有解决方案之间的速度差。我可能有点偏颇,但我个人会坚持使用一行代码,因为我们讨论的速度与为这个问题创建函数和导入模块相比是微不足道的,但是如果您计划对大量元素执行此操作,您可能需要查看提供的其他答案,因为它们比我提供的要快提供。

一种可能是使用operator模块中的itemgetter函数:

import operator

f = operator.itemgetter(0)
print map(f, tuple_list).index("cherry") # yields 1

itemgetter的调用返回一个函数,该函数将对传递给它的任何内容执行与foo[0]等价的操作。使用map,然后将该函数应用于每个元组,将信息提取到新列表中,然后在该列表上正常调用index

map(f, tuple_list)

相当于:

[f(tuple_list[0]), f(tuple_list[1]), ...etc]

这又相当于:

[tuple_list[0][0], tuple_list[1][0], tuple_list[2][0]]

它给出:

["pineapple", "cherry", ...etc]

相关问题 更多 >