Kalanamith Kalanamith - 4 months ago 7
Python Question

Python list operations , Lambda Expression

def myFunction(name):
index = 0
list = self.getList()
index = (x => x.name == name)
return index

i want to use lamba expression to find an index of an element in a python list just as in C#. is it possible to use lambda expressions just as in C# to find an index of a specific element in python list . If so please provide an example


I think this code is closer to what you are asking for:

def indexMatching(seq, condition):
    for i,x in enumerate(seq):
        if condition(x):
            return i
    return -1

class Z(object):
    def __init__(self, name):
        self.name = name

class X(object):
    def __init__(self, zs):
        self.mylist = list(zs)

    def indexByName(self, name):
        return indexMatching(self.mylist, lambda x: x.name==name)

x = X([Z('Fred'), Z('Barney'), Z('Wilma'), Z('Betty')])

print x.indexByName('Wilma')

Returns 2.

The key idea is to use enumerate to maintain an index value while iterating over the sequence. enumerate(seq) returns a series of (index,item) pairs. Then when you find a matching item, return the index.