Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping arrays in Python using map, lambda, and functional programming workflows

I'm trying to understand how functional programming languages work, and I decided to take the approach of program in a functional way in python, as it is the language in which I feel more comfortable.

I'm trying to, given an array of arrays and a function with 2 params, get two sentences with the two elements in each array.

I cannot figure out how to do it without nesting lambdas, but even using them:

def sentence( x, y):
    return " this string contains %s and %s" % (x,y)
matrix = [['a','b'],['c','d']]

output = map(lambda a: map(lambda b: map(lambda c,d: sentence(c,d),b),a),matrix)

Of course, because a I am a old fashioned imperative programmer, I try to get the output with the good old for loop. Sure there's a better way but...

#print(output)
for i in output:
    #print(i)
    for j in i:
        #print(j)
        for k in j:
            print(k)

At the end I only get this result:

  File "fp.py", line 12, in <module>
    for k in j:
TypeError: <lambda>() missing 1 required positional argument: 'd'

So yes, I guess I'm doing something wrong passing the values to the function, but I cannot guess why.

Any ideas?

like image 881
JMartinez Avatar asked Jul 02 '26 07:07

JMartinez


1 Answers

  1. Python style guide recommends using list comprehensions instead of map/reduce
  2. String formatting using percent operator is obsolete, consider using format() method
  3. the code you need is this simple one-liner

    output = [" this string contains {} and {}".format(x, y) for (x, y) in matrix]

like image 174
Arseniy Avatar answered Jul 03 '26 20:07

Arseniy