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

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

    No body suggest lambdas?

    Y try this and works. I come to this post searching answer. I don't found that I like, but I feel a insingth :P

        l #[['rana', 1, 1], ['pato', 1, 1], ['perro', 1, 1]]
    
        map(lambda x:x[0], l).index("pato") #1 
    

    Edit to add examples:

       l=[['rana', 1, 1], ['pato', 2, 1], ['perro', 1, 1], ['pato', 2, 2], ['pato', 2, 2]]
    

    extract all items by condition: filter(lambda x:x[0]=="pato", l) #[['pato', 2, 1], ['pato', 2, 2], ['pato', 2, 2]]

    extract all items by condition with index:

        >>> filter(lambda x:x[1][0]=="pato", enumerate(l))
        [(1, ['pato', 2, 1]), (3, ['pato', 2, 2]), (4, ['pato', 2, 2])]
        >>> map(lambda x:x[1],_)
        [['pato', 2, 1], ['pato', 2, 2], ['pato', 2, 2]]
    

    Note:_ variable only works in interactive interpreter y normal text file _ need explicti assign, ie _=filter(lambda x:x[1][0]=="pato", enumerate(l))

提交回复
热议问题