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

前端 未结 12 1491
说谎
说谎 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条回答
  •  Happy的楠姐
    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]
    

提交回复
热议问题