Python List Operations, Lambda Expression

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

I want to use the lamba expression to find the index of an element in a python list, as in C #. Is it possible to use lambda expressions just like in C # to find the index of a specific element in a python list. If yes, please provide an example.

+4
source share
4 answers

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

 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 basic idea is to use an enumeration to maintain the index value when iterating over a sequence. enumerate(seq) returns a series of pairs (index, element). Then, when you find the matching item, return the index.

+3
source

Lists in python already have a built-in function

 >>> a = ['foo','bar','buz'] >>> a.index('bar') 1 >>> a.index('foo') 0 
+5
source

If you really want to use lambda, the syntax is:

 lambda param, list: return_value 

For example, this is lamdba, which adds:

 lambda x, y: x + y 

I'm not sure how this could make your function easier, as this is the most obvious way:

 def myFunction(name): for i, x in enumerate(self.getList()): if x.name == name: return i 

Your lamdba would be like this:

 lamdba x: x.name == name 

So, one terrible way to do this:

 def myFunction(name): matches = [index for index, value in enumerate(self.getList()) if value.name == name] if matches: return matches[0] 
+3
source

Perhaps you can do:

 idx = [i for i, a in enumerate(lst) if a.name == name][0] 
+1
source

Source: https://habr.com/ru/post/1381843/


All Articles