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

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

    Python's list.index(x) returns index of the first occurrence of x in the list. So we can pass objects returned by list compression to get their index.

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

    With the same line, we can also get the list of index in case there are multiple matched elements.

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

提交回复
热议问题