How to start a collection operation in Python and collect the results?

How to run an operation in a collection in Python and collect the results?

So, if I have a list of 100 numbers, and I want to run such a function for each of them:

Operation ( originalElement, anotherVar ) # returns new number. 

and get the result as follows:

result = another list ...

How can I do it? Maybe use lambdas?

+4
source share
3 answers

List of concepts. In Python, they look something like this:

 a = [f(x) for x in bar] 

Where f (x) is a function and bar is a sequence.

You can define f (x) as a partially applied function with a construction similar to:

 def foo(x): return lambda f: f*x 

A function will be returned that multiplies the parameter by x. A trivial example of this type of construct used in list comprehension is as follows:

 >>> def foo (x): ... return lambda f: f*x ... >>> a=[1,2,3] >>> fn_foo = foo(5) >>> [fn_foo (y) for y in a] [5, 10, 15] 

Although I do not intend to use such a design in any, but rather esoteric cases. Python is not a true functional language, so it has less ability to do smart tricks with higher order functions than (say) Haskell. You can find applications for this type of construction, but this is not exactly what pythonic is. You could achieve a simple transformation with something like:

 >>> y=5 >>> a=[1,2,3] >>> [x*y for x in a] [5, 10, 15] 
+12
source

Another (somewhat depreciated) way to do this:

def kevin (v): return v * v

vals = range (0,100)

map (Kevin Vals)

+1
source

All Articles