Python的列表的类型有一个索引()方法,它的一个参数,并返回所述第一项的索引在参数匹配的列表中。例如:

>>> 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是否已经有一个办法做到这一点。

有帮助吗?

解决方案

这个怎么样?

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

有在批示张贴的所有解决方案之间的速度差了很好的讨论。我可能有点偏颇,但我个人坚持一个班轮因为我们谈论的速度是非常微不足道的对创建函数和导入模块对于这个问题,但如果你是做这个的非常大的量计划元素,你可能想看看提供的其他的答案,因为他们比我提供什么更快。

其他提示

这些列表解析是一段时间后凌乱。

我喜欢这个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

一种可能性是使用 itemgetter 函数从operator模块:

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]

可以与列表中理解和索引做到这一点()

tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
[x[0] for x in tuple_list].index("kumquat")
2
[x[1] for x in tuple_list].index(7)
1

我会将此作为三联评论,但是由于缺乏评价我尚未对此发表评论:

使用枚举方法以匹配在元组的列表子索引。 e.g。

li = [(1,2,3,4), (11,22,33,44), (111,222,333,444), ('a','b','c','d'),
        ('aa','bb','cc','dd'), ('aaa','bbb','ccc','ddd')]

# want pos of item having [22,44] in positions 1 and 3:

def getIndexOfTupleWithIndices(li, indices, vals):

    # if index is a tuple of subindices to match against:
    for pos,k in enumerate(li):
        match = True
        for i in indices:
            if k[i] != vals[i]:
                match = False
                break;
        if (match):
            return pos

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

idx = [1,3]
vals = [22,44]
print getIndexOfTupleWithIndices(li,idx,vals)    # = 1
idx = [0,1]
vals = ['a','b']
print getIndexOfTupleWithIndices(li,idx,vals)    # = 3
idx = [2,1]
vals = ['cc','bb']
print getIndexOfTupleWithIndices(li,idx,vals)    # = 4
通过 href="https://stackoverflow.com/questions/35446421/finding-a-specific-value-from-list-of-dictionary-in-python#35446432">这个问题,我发现这个相当优雅:

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

确定,它可能是在vals(j)一个错误,校正是:

def getIndex(li,indices,vals):
for pos,k in enumerate(lista):
    match = True
    for i in indices:
        if k[i] != vals[indices.index(i)]:
            match = False
            break
    if(match):
        return pos
tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]

def eachtuple(tupple, pos1, val):
    for e in tupple:
        if e == val:
            return True

for e in tuple_list:
    if eachtuple(e, 1, 7) is True:
        print tuple_list.index(e)

for e in tuple_list:
    if eachtuple(e, 0, "kumquat") is True:
        print tuple_list.index(e)
z = list(zip(*tuple_list))
z[1][z[0].index('persimon')]

没有身体建议的lambda?

ÿ试试这个和作品。我来这个帖子的搜索答案。我不发现我很喜欢,但我觉得一个insingth:P

    l #[['rana', 1, 1], ['pato', 1, 1], ['perro', 1, 1]]

    map(lambda x:x[0], l).index("pato") #1 

编辑补充例子:

   l=[['rana', 1, 1], ['pato', 2, 1], ['perro', 1, 1], ['pato', 2, 2], ['pato', 2, 2]]

提取由条件所有项目:         过滤器(拉姆达X:X [0] == “帕托”,L)#[[ '帕托',2,1],[ '帕托',2,2],[ '帕托',2,2]]

提取与索引由条件所有项目:

    >>> filter(lambda x:x[1][0]=="pato", enumerate(l))
    [(1, ['pato', 2, 1]), (3, ['pato', 2, 2]), (4, ['pato', 2, 2])]
    >>> map(lambda x:x[1],_)
    [['pato', 2, 1], ['pato', 2, 2], ['pato', 2, 2]]

注意:_变量只能在交互解释y标准文本文件_需要explicti分配,即_ =过滤(拉姆达X:X [1] [0] == “帕托”,列举(1))

Python的list.index(x)返回x的列表中的第一次出现的索引。因此,我们可以通过传递压缩列表返回得到他们的索引对象。

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

使用相同的线,我们也可以得到索引的情况下,在列表中存在多个匹配的元素。

>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11), ("banana", 7)]
>>> [tuple_list.index(t) for t in tuple_list if t[1] == 7]
[1, 4]

我想下面是不是这样做(速度和优雅问题)的最佳方式,但很好,它可以帮助:

from collections import OrderedDict as od
t = [('pineapple', 5), ('cherry', 7), ('kumquat', 3), ('plum', 11)]
list(od(t).keys()).index('kumquat')
2
list(od(t).values()).index(7)
7
# bonus :
od(t)['kumquat']
3

用2元组成员列表可以被转化成有序的dict直接,数据结构实际上是相同的,所以我们可以对飞使用字典方法。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top