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

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

    I guess the following is not the best way to do it (speed and elegance concerns) but well, it could help :

    from collections import OrderedDict as od
    t = [('pineapple', 5), ('cherry', 7), ('kumquat', 3), ('plum', 11)]
    list(od(t).keys()).index('kumquat')
    2
    list(od(t).values()).index(7)
    7
    # bonus :
    od(t)['kumquat']
    3
    

    list of tuples with 2 members can be converted to ordered dict directly, data structures are actually the same, so we can use dict method on the fly.

提交回复
热议问题