Using Python's list index() method on a list of tuples or objects?

前端 未结 12 1459
说谎
说谎 2020-12-12 12:15

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:



        
相关标签:
12条回答
  • 2020-12-12 12:38

    How about this?

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

    0 讨论(0)
  • 2020-12-12 12:44

    One possibility is to use the itemgetter function from the operator module:

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

    The call to itemgetter returns a function that will do the equivalent of foo[0] for anything passed to it. Using map, you then apply that function to each tuple, extracting the info into a new list, on which you then call index as normal.

    map(f, tuple_list)
    

    is equivalent to:

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

    which in turn is equivalent to:

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

    which gives:

    ["pineapple", "cherry", ...etc]
    
    0 讨论(0)
  • 2020-12-12 12:44

    I would place this as a comment to Triptych, but I can't comment yet due to lack of rating:

    Using the enumerator method to match on sub-indices in a list of tuples. 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','ffffd')]
    
    # 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
    
    0 讨论(0)
  • 2020-12-12 12:44

    ok, it might be a mistake in vals(j), the correction is:

    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
    
    0 讨论(0)
  • 2020-12-12 12:46
    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)
    
    0 讨论(0)
  • 2020-12-12 12:48

    I guess the following is not the best way to do it (speed and elegance concerns) but well, it could help :

    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
    

    list of tuples with 2 members can be converted to ordered dict directly, data structures are actually the same, so we can use dict method on the fly.

    0 讨论(0)
提交回复
热议问题