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

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

    Inspired by this question, I found this quite elegant:

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

提交回复
热议问题