Python: how to create a pointer to a function with a given argument?

My problem:

Given the following:

def foo(a,b)

I am trying to call the python "map" function when passing in a list for "a", but using the given value for "b."

Another important fact is that "b" is entered by the user, and therefore I cannot use the syntax:

def foo(a,b='default value')

I want my "map" call to look like this:

map(foo_wrapper,list_for_a)

where 'foo_wrapper' is some function that accepts 'a' but uses the user-specified 'b.'

I do not know if it is possible to point to function pointers and not suspect that they cannot.

My solution to this problem is using global variables, so if a more elegant way and above is not possible, I will also mark this as an answer.

Here is my solution in a nutshell:

b = ''
def foo(a,b):
  print b,a

def foo_wrapper(a):
  foo(a,b)

def main():
  if sys.argv[1]:
    a = ['John', 'Jacob', 'Jingle all the way']
    global b
    b = sys.argv[1]
    map(foo_wrapper,a)

; , .

!

+3
3

functools.partial() :

from functools import partial

def f(a, b):
    return a + b

x = range(10)
print map(partial(f, b=3), x)

[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
+7

- . :

map(lambda x: f(x,3), a)
+7

[f(x, your_set) for x in your_list]

, , ( Python 3).

(f(x, your_set) for x in your_list)

Edit:

, :

L = ['John', 'Jacob', 'Jingle all the way']
[foo(a, b=b) for a in L]

- map lambda. :

L2 = map(lambda arg: f(arg) + arg, L1)
L2 = map(lambda (x,y): x + y, L1)
L2 = map(lambda <arg>: <expression>, L1)

:

L2 = [f(arg) + arg for arg in L1]
L2 = [x + y for x, y in L1]
L2 = [<expression> for <arg> in L1]

Generator expressions are similar, but instead of a list, they return a lazy iterator and are written using parsers instead of square brackets. (And since mapPython 3 is modified so as not to return lists, its equivalent is a generator expression.) Sometimes a list is not needed, for example, when you want to do:

','.join(map(lambda x: x.upper(), L))

The concept of an equivalent list:

','.join([x.upper() for x in L])

But you really don't need a list, so you can just do:

','.join(x.upper() for x in L)
+1
source

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


All Articles