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

前端 未结 12 1496
说谎
说谎 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: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
    

提交回复
热议问题