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

前端 未结 12 1513
说谎
说谎 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.

提交回复
热议问题